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

javascript - how to get child node by tag name - Stack Overflow

programmeradmin4浏览0评论

I am trying to access child nodes. so far so good. my code is

columns = document.getElementById('columns').children[0].children;

where i and j are loops values.

collapseState = columns[i].children[j].children[2].style.display;

But i am try to get the element by tag name. Lets write:

collapseState = columns[i].children[j].children.getElementsByTagName('blahblah');

but it gives error. How to achieve this ?

I am trying to access child nodes. so far so good. my code is

columns = document.getElementById('columns').children[0].children;

where i and j are loops values.

collapseState = columns[i].children[j].children[2].style.display;

But i am try to get the element by tag name. Lets write:

collapseState = columns[i].children[j].children.getElementsByTagName('blahblah');

but it gives error. How to achieve this ?

Share Improve this question edited Jun 6, 2016 at 14:09 Venkata Krishna 15.1k5 gold badges44 silver badges57 bronze badges asked Jun 6, 2016 at 14:06 waleedansariwaleedansari 1971 gold badge3 silver badges16 bronze badges 6
  • VM217:1 Uncaught TypeError: columns[i].children[j].children.getElementsByClassName is not a function(…) – waleedansari Commented Jun 6, 2016 at 14:07
  • .children is an HtmlCollection. It does not have that function. An individiual node would have that function. For instance, .children[0].getElementsByClassName(....) – adam-beck Commented Jun 6, 2016 at 14:08
  • See: developer.mozilla/en-US/docs/Web/API/ParentNode/children and developer.mozilla/en-US/docs/Web/API/HTMLCollection – adam-beck Commented Jun 6, 2016 at 14:10
  • 1 querySelectorAll('#columns blahblah') – adeneo Commented Jun 6, 2016 at 14:10
  • 1 What is the HTML, I am betting there is a better way. – epascarello Commented Jun 6, 2016 at 14:11
 |  Show 1 more ment

2 Answers 2

Reset to default 9

Your problem stems from trying to use a function that doesn't exist on an HtmlCollection. You would need to grab an individual ParentNode in order to use the getElementsByTagName or getElementsByClassName functions.

collapseState = columns[i].children[j].getElementsByTagName('blahblah'); or

collapseState = columns[i].children[j].children[someIndex].getElementsByTagName('blahblah');

may be this could help you

function getbytagname(parents_id, children_tag_name){
var c = document.getElementById(parents_id).children;
var x = [] ;
for(var i =0; i<c.length;i++)
 {
  if(c[i].tagName===children_tag_name){ // children_tag_name should be in capital, eg. "SPAN"
   x.push(c[i]);
  }
 };
return x;
}

this is just to give you an idea, you can modify this as per your requirements

发布评论

评论列表(0)

  1. 暂无评论