0

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" ?

Filou
  • 11
  • 2

2 Answers2

0

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"); });
Shuky25
  • 1
  • 1
  • Hello! Thank you for the time you took to answer me :). The problem is that I don't know by advance what are the children. The only way the function may know by itself what are the children is by storing the object in the variable and use the object property "children" that has as property an HTMLcollection. – Filou Dec 30 '22 at 18:56
0

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

Yarin_007
  • 1,449
  • 1
  • 10
  • 17