The native javascript implementation gets a method for all descendant elements under a specified element

  • 2020-03-30 04:13:48
  • OfStack

This article is an example of how a native javascript implementation can get all the descendants of a given element. The specific implementation method is as follows:

The old way of looping recursion is a bit cumbersome, but here's a simple way to do it using native javascript methods.
The code example is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.jb51.net/" />
<title>javascript Get descendant elements </title>
<script type="text/javascript">
window.onload=function(){
  var obox=document.getElementById("box");
  var oshow=document.getElementById("show");
  var nodes=obox.getElementsByTagName("*");
  oshow.innerHTML=nodes.length;
}
</script>
</head>
<body>
<div id="show"></div>
<div id="box">
  <div>
    <ul>
      <li> Elements of a </li>
      <li> Element 2 </li>
      <li> Three elements </li>
    </ul>
  </div>
</div>
</body>
</html>

The above code implements our requirements, and the parameter asterisk represents a wildcard that matches all types of tags.
The calling object of the getElementsByTagName() method determines its lookup scope.


Related articles: