Johnathon64
Johnathon64

Reputation: 1320

Get id attribute from a node in nodelist

I have currently got a nodelist by using the document.getElementsByClassName method in javascript. I then check if the first node has any children and if not I would return a document.getElementById with that nodes ID. I am unsure of how to get the ID from the node list.

 var columns = document.getElementsByClassName('.col-md-4.column');

if (countChildren(columns[0].childNodes) == 0) {
    return document.getElementById(columns[0].) //not sure what goes here
}

Upvotes: 2

Views: 10236

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

Not surprisingly, it's .id:

return document.getElementById(columns[0].id);

But more importantly, you already have a reference to the node - don't query the DOM for it:

return columns[0];

Upvotes: 1

adeneo
adeneo

Reputation: 318182

If you have a DOM node, it has an id property, you can't use getElementById to get that property

var columns = document.querySelectorAll('.col-md-4.column');

if ( countChildren(columns[0].childNodes) == 0 ) {
    return columns[0].id;
}

Note that getElementsByClassName takes the classes without the period, but for better support you might as well use querySelectorAll

Upvotes: 3

Related Questions