Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 681
Ivan Avatar asked Jan 22 '14 23:01

Ivan


People also ask

How do I find the class inside a div?

Try: $('#mydiv'). find('. myclass');

How do you select all elements inside a division element?

Use the element element selector to select all elements inside another element.

Can you get element by class in JavaScript?

The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.


1 Answers

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];
like image 69
adeneo Avatar answered Oct 20 '22 21:10

adeneo