Using QuerySelector for nested elements
Need to change the text of nested HTML element with specific class names and thought this was a good use of document.querySelector. This way I can use CSS type selectors to find the element and then modify the text as needed
Example: I have the following
<div class="level1">
<h2 class="specialLabel">Text to Change</h2>
</div>
Now I want to change h2 Text to Change
to say Change for the better
and to be clear there are numerous other divs and h2 in this div that I am not showing for brevity.
Solution
<script>
window.addEventListener("load", (event) => {
const titleElement = document.querySelector("div.level1 h2.specialLabel");
if (titleElement !== null) {
titleElement.innerText = "Change for the better";
}
});
</script>