WhiZTiM
WhiZTiM

Reputation: 21576

How to get all Child Elements with specific attribute in JavaScript

I have an object that was retrieved from this expression:

const element = document.querySelector("...my selector...");

I need to get all child elements that have certain attributes, The only way I know to get all children is by:

const children = Array.from(element.childNodes);

but now each child in children is not an element, rather a node, hence, I cannot use getAttribute('') on them;

How do I "cast" a Node to an Element?, Or is there a better way to do this?

Upvotes: 5

Views: 17664

Answers (3)

epascarello
epascarello

Reputation: 207501

You said you want to select all children with a specific attribute. So select them with querySelectorAll using an attribute selector.

var elems = document.querySelectorAll("#theParentSelector > [theChildsAttribute]")
console.log(elems.length)
Array.from(elems).forEach( function (el) {
   console.log(el.getAttribute("theChildsAttribute"))
});
<div id="theParentSelector">
  <div theChildsAttribute="1">Foo 1</div>
  <div>Bar</div>
  <div theChildsAttribute="2">Foo 2</div>
  <div theChildsAttribute="3">Foo 3</div>
</div>

Upvotes: 6

Carl Edwards
Carl Edwards

Reputation: 14434

You'd use children to gain access to all HTML based nodes:

document.querySelector("...my selector...").children

Upvotes: 3

Quentin
Quentin

Reputation: 943510

How do I "cast" a Node to an Element?

You can't.

Elements are a subset of Nodes.

If it isn't an Element already, then you can't turn it into one.

Consider:

<div>Hello, <strong>World</strong></div>

You have two child nodes. The text node "Hello, " and the strong element node.

It doesn't make sense to treat "Hello, " as an element.


Consider using children instead of childNodes. It fetches only element children.


I need to get all child elements that have certain attributes

In that case, you're probably better off just using a selector which gets you that in the first place. You'll need a child combinator and an attribute selector in addition to your existing selector. Then you'll need to use All to get more than one result.:

document.querySelectorAll("...my selector... > [someAttribute]"

Upvotes: 9

Related Questions