jQuery children() map each child

Introduction

In this example, $("div").children will only return P, and not P + SPAN.

children() only traverse a single level down the DOM tree.

View in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var treeTraversal = $("div").children().map(function(){
  return this.tagName;}).get().join(", ");
  $("div").after("<h2>" + treeTraversal + "<h2>");
});//ww  w . ja  va2  s. c  om
</script>
</head>

<body>
  <div> This is a div element. 
      My child is:
    <p>
      <span></span>
    </p>
    <p>
      <span></span>
    </p>
    <p>
      <span></span>
    </p>
  </div>
</body>
</html>



PreviousNext

Related