最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get id attribute from a node in nodelist - Stack Overflow

programmeradmin1浏览0评论

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
}

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
}
Share Improve this question asked Jun 1, 2015 at 10:04 Johnathon64Johnathon64 1,3202 gold badges21 silver badges47 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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

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];
发布评论

评论列表(0)

  1. 暂无评论