Sometimes, we want to access an HTML element without an ID with JavaScript.
In this article, we’ll look at how to access an HTML element without an ID with JavaScript.
How to access an HTML element without an ID with JavaScript?
To access an HTML element without an ID with JavaScript, we can use document.querySelector
.
For instance, we write:
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
to add a div with an h1 element in it.
Then to select the h1 element, we write:
const h1 = document.querySelector('#header-inner h1')
console.log(h1)
We use the '#header-inner h1'
select to select the h1 element inside the div with ID header-inner
.
Therefore, the h1 element is logged.
Conclusion
To access an HTML element without an ID with JavaScript, we can use document.querySelector
.