Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Only document.getElementbyID is working. no other JS DOM selector is working

What I have tried:

HTML
<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <div>
            <h1 ></h1>
            <h1 id="test"></h1>
            
        </div>
        <script src="test.js"></script>
    </body>
</html>


JavaScript
document.querySelectorAll('h1').innerHTML="Hello";
document.getElementsByTagName('h1').innerHTML="test";
document.getElementById('test').innerHTML="hello";
Posted
Updated 29-Jul-21 21:50pm

1 solution

You need to start reading the documentation for the functions that you're calling. If you don't understand what the return values of these methods are then you'll constantly need to ask for support.

Document.querySelectorAll() - Web APIs | MDN[^]
Document.getElementsByTagName() - Web APIs | MDN[^]

Unlike your previous question[^] these functions return a collection of values, which means there could be more than one result. You can't call .innerHTML on a collection, you need to iterate over them:
JavaScript
const matches = document.querySelectAll('h1');

for (let i = 0; i < matches.length; i++) {
  matches[i].innerHTML = 'I am a header #' + i;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900