Reputation: 21
I have an index.html like so:
<div id="mydiv">
Text inside div
<h1>
Header inside div
</h1>
</div>
<h1>
Header outside div
</h1>
And my style.css looks like this:
#mydiv h1 {
color: blue;
}
To change the color of "Text inside div" with JS, I can do this:
document.getElementById("mydiv").style.color = "red";
But how do I change the color of "Header inside div" using only JS? (without modifying the HTML or CSS or changing h1 outside the div)
Upvotes: 1
Views: 5207
Reputation: 81
Here is one way to do it
document.querySelector('#mydiv h1').style.color = "green";
This will select the h1 element inside the div.
Using document.querySelector
is really powerful and makes manipulations like this easy. Check out the Document.querySelector()
Upvotes: 0
Reputation: 10194
Using document.querySelector
, you can select h1
tag inside #mydiv
selector.
document.getElementById("mydiv").style.color = "red";
document.querySelector("#mydiv h1").style.color = "yellow";
#mydiv h1 {
color: blue;
}
<div id="mydiv">
Text inside div
<h1>
Header inside div
</h1>
</div>
<h1>
Header outside div
</h1>
Upvotes: 4