How to get elements of a specific class inside a div already found in JavaScript?

I need to find a div with a specific id, and then find in it some element with a specific class and make the first one invisible. I tried

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

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

Object #<NodeList> has no method 'getElementsByClassName'

mistake.

So what is the right way? I would rather use pure JavaScript (rather than jQuery or something else) as far as it seems reasonable.

+4
source share
1 answer

If this is an identifier, why are you using getElementsByName, notgetElementById

var hostDivName = "theHostDivName";

var hostDiv = document.getElementById(hostDivName);

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

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

Assuming you meant a name, not an ID

var hostDiv = document.getElementsByName(hostDivName)[0];
+9
source

All Articles