skip to Main Content

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


  1. 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"); });
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search