Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

JavaScript - get element by id name with code example

0 contributions
2 points

In JavaScript it is possible to get element handle by id in following ways.

1. document.getElementById method example

First example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="my-element">Some text here...</div>
  <script>
  
    var handle = document.getElementById('my-element');

    handle.style.background = 'red';

  </script>
</body>
</html>

Result:

document.querySelectorAll usage example
document.querySelectorAll usage example

Second example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="exampleId">Original text.</div>
  <button onclick="changeText()">Change Text Button</button>
  <script>
    
    var element = document.getElementById('exampleId');
    
    function changeText() {
        element.innerHTML = "Changed text.";
    }
    
  </script>
</body>
</html>

2. document.querySelector method example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="my-element">Some text here...</div>
  <script>
  
    var handle = document.querySelector('#my-element');

    handle.style.background = 'red';

  </script>
</body>
</html>

Result:

document.querySelectorAll usage example
document.querySelectorAll usage example

Note: document.querySelector method uses css selectors - it means each id name should be prefixed with hash.

3. document.querySelectorAll method example

Writing web page it is possible to define few elements with same id attribute - this aproach is strongly not recommended because of id was designed to be unique.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="my-element">Some text here...</div>
  <div id="my-element">Some text here...</div>
  <div id="my-element">Some text here...</div>
  <script>
  
    var handles = document.querySelectorAll('#my-element');

    for(var i = 0; i < handles.length; ++i)
      handles[i].style.background = 'red';

  </script>
</body>
</html>

Result:

document.querySelectorAll usage example
document.querySelectorAll usage example
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more