Home > Enterprise >  jQuery: contents() function don't return children of children
jQuery: contents() function don't return children of children

Time:01-02

In my case I'm using the .contents() instead of the .children() because the .contents() supports text nodes, which is not the case of .children() . I have this code:

<body>
  blablabla
  <p>example</p>
  <div>
    <a>link</a>
  </div>
</body>

var body_content = $("body").contents();

The body_content variable would return 3 nodes: a text node, a paragraph node and a div node, while I expect it to return the anchor node that is located in the div. I looked for an alternative in the jQuery documentation and I didn't find any function that does what I want. Are there ways to do it "manually" ?

CodePudding user response:

To get the anchor node that is located inside the div element, you can use the find method:

var anchor = $("body div").find("a");

This will return the anchor node that is a descendant of the div element. If you want to get all the anchor nodes that are descendants of the body element, you can use the $("body a") selector. Alternatively, you can use the filter method to filter out the nodes that you want from the body_content variable:

var anchor = body_content.filter(function() { return this.nodeName === "A"; });

This will return an array of anchor nodes that are descendants of the body element. You can also use the is method to check if a node is an anchor element:

var anchor = body_content.filter(function() { return $(this).is("a"); });

CodePudding user response:

I'm not sure what you're trying to accomplish. Maybe the following will help

console.log(document.body.querySelectorAll("*"))
<body>
  blablabla
  <p>example</p>
  <div>
    <a>link</a>
  </div>
</body>

Or perhaps https://stackoverflow.com/a/61579622/4935162 or https://stackoverflow.com/a/41051238/4935162

  • Related