Sometimes, we want to select nested element with class with JavaScript.
In this article, we’ll look at how to select nested element with class with JavaScript.
How to select nested element with class with JavaScript?
To select nested element with class with JavaScript, we can use the querySelector
method.
For instance, we write:
<div class="cl1">
<h1>Some heading</h1>
<div class="sl-desc">Some description</div>
<div class="sl-price">from only $10</div>
</div>
to add a div with nested divs.
Then we can select the div with class s1-price
in the div with class cl1
by writing:
const el = document.querySelector(".cl1 .sl-price")
console.log(el.textContent)
We call document.querySelector
with ".cl1 .sl-price"
to do the selection.
And then we use the textContent
property to get its text content.
Therefore, the console log logs "from only $10"
.
Conclusion
To select nested element with class with JavaScript, we can use the querySelector
method.