4

I've simple javascript to get it's child element with the getElementsByClassName but it's not working:

var parent = document.getElementsByClassName('parent');
var child = parent.getElementsByClassName('child');
child.style.color='red';

I've tried a lot and searched to get it but some answers with for loop I've found but I wanted to do it without loop. How can I do this?

user3556821
  • 59
  • 1
  • 1
  • 3
  • 2
    Well `getElementsByClassName` returns a list of elements so you're going to have to use a loop. – Niklas Apr 30 '14 at 09:08
  • If you are looking to manipulate only the first child matching the class (or if you are certain there is only one child matching the class), you can do: `child[0].style.color='red';` – techfoobar Apr 30 '14 at 09:09
  • Why not to use jQuery? "$('.parent .child').css('color', 'red')" – Justinas Apr 30 '14 at 09:10
  • techfoobar -- I also tried this: child[0].style.color='red'; but not working. – user3556821 Apr 30 '14 at 09:12

3 Answers3

5

You can get the complete node list in one step

var children = document.querySelectorAll(".parent .child");

But then you'll have to loop over that node list.

If you are really interested in only the first one, then you can do

document.querySelector(".parent .child").style.color = 'red';
Thilo
  • 257,207
  • 101
  • 511
  • 656
2

Try this:

var parent = document.getElementsByClassName('parent');
for(var i=0;i<parent.length;i++){
  var child = parent[i].getElementsByClassName('child');
for(var j=0;j<child.length;j++){
      child[j].style.color='red';
    }

}

document.getElementsByClassName() return the collection. So you have to apply indexing or looping.

Naveen Chandra Tiwari
  • 5,055
  • 3
  • 20
  • 26
1

Multiple elements can be members of the same class. That is the point of classes.

In getElementsByClassName the word elements is plural. It returns a NodeList, not a single Element.

You can treat it much like an array. You have to loop over each of the nodes that it returns or assume that it will only return one match and use [0].

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335