Ciprian
Ciprian

Reputation: 3226

Get childNode attributes with JavaScript

I'm trying to get the attributes of an element's children ... something like this:

<div id="mydivs">
  <div name="mydiv1" name="format1">

  </div>
  <div name="mydiv2" format="format2">

  </div>
</div>


var parent = document.getElementById('mydivs');

var children = parent.childNodes;

for (let child of children) {
  console.log(child)
  console.log(child.attributes)
}

child.atrribute returns undefined

JsFiddle: https://jsfiddle.net/8tdac5fn/

Edit: Another option would be to use children instead of childNodes

var parent = document.getElementById('mydivs');
var children = parent.children;

Upvotes: 3

Views: 206

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122077

parent.childNodes will include text nodes and that is why you are getting undefined, so you can first check if nodeType is 1 which is Node.ELEMENT_NODE.

Then you could use spread syntax in array to create array of attribute nodes so you can use forEach loop.

var parent = document.getElementById('mydivs');
var children = parent.childNodes;

for (let child of children) {
  if (child.nodeType === 1) {
    [...child.attributes].forEach(({name,value}) => {
      console.log(`${name} - ${value}`);
    })
  }
}
<div id="mydivs">
  <div name="mydiv1" name="format1"></div>
  <div name="mydiv2" format="format2"></div>
</div>

Upvotes: 3

Related Questions