Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get child element with getElementsByClassName? [duplicate]

Tags:

javascript

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?

like image 603
user3556821 Avatar asked Oct 18 '25 14:10

user3556821


1 Answers

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';
like image 55
Thilo Avatar answered Oct 21 '25 04:10

Thilo