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

html - How to get elements of specific class inside a div already found in JavaScript? - Stack Overflow

programmeradmin9浏览0评论

What I need is to find a div with particular id, then find any element with particular class inside it and make the first of them invisible. I have tried

var hostDivName = "theHostDivName";
var hostDiv = document.getElementsByName(hostDivName);
var theElements = hostDiv.getElementsByClassName("theClassDivName");
theElements[0].style.display = "none";

But it fails on hostDiv.getElementsByClassName("theClassDivName"); with

Object #<NodeList> has no method 'getElementsByClassName'

error.

So what is the right way? I'd prefer using pure JavaScript (rather than jQuery or whatever) as far as this seems reasonable.

What I need is to find a div with particular id, then find any element with particular class inside it and make the first of them invisible. I have tried

var hostDivName = "theHostDivName";
var hostDiv = document.getElementsByName(hostDivName);
var theElements = hostDiv.getElementsByClassName("theClassDivName");
theElements[0].style.display = "none";

But it fails on hostDiv.getElementsByClassName("theClassDivName"); with

Object #<NodeList> has no method 'getElementsByClassName'

error.

So what is the right way? I'd prefer using pure JavaScript (rather than jQuery or whatever) as far as this seems reasonable.

Share Improve this question asked Jan 22, 2014 at 23:53 IvanIvan 64.2k101 gold badges262 silver badges394 bronze badges 2
  • 1 getElementsBy* functions return an array of elements, you need to loop through it. – Patrick Evans Commented Jan 22, 2014 at 23:56
  • Thanks, @PatrickEvans, indeed, seems obvious when you get it... – Ivan Commented Jan 23, 2014 at 0:04
Add a ment  | 

1 Answer 1

Reset to default 17

If it's an ID, why are you using getElementsByName and not getElementById

var hostDivName = "theHostDivName";

var hostDiv = document.getElementById(hostDivName);

var theElements = hostDiv.getElementsByClassName("theClassDivName");

theElements[0].style.display = "none";

Assuming you meant name, and not ID

var hostDiv = document.getElementsByName(hostDivName)[0];
发布评论

评论列表(0)

  1. 暂无评论