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" ?
2
Answers
To get the anchor node that is located inside the div element, you can use the
find
method: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: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:I’m not sure what you’re trying to accomplish.
Maybe the following will help
Or perhaps https://stackoverflow.com/a/61579622/4935162 or https://stackoverflow.com/a/41051238/4935162