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
1 Answer
Reset to default 17If 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];