Languages
[Edit]
EN

JavaScript - get element handle by id

10 points
Created by:
JustMike
3488

In this article, we're going to have a look at how to get element by id in JavaScript. 

We can achieve it by using one of the methods available by default in JavaScript:

  • document.getElementById('element-id')
  • document.querySelector('#element-id')
  • document.querySelectorAll('#element-id')

Below we can see runnable examples of each of those methods. Click on it to test how it works.

1. with document.getElementById:

// ONLINE-RUNNER:browser;

<html>
  <body>
    <div id="my-element">Nothing inside...</div>
    <script>

	var handle = document.getElementById( 'my-element' );

	handle.innerHTML = 'Some <b>text</b> inside...';

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

2. with document.querySelector:

// ONLINE-RUNNER:browser;

<html>
  <body>
    <div id="my-element">Nothing inside...</div>
    <script>

	var handle = document.querySelector( '#my-element' );

	handle.innerHTML = 'Some <b>text</b> inside...';

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

3. with document.querySelectorAll:

// ONLINE-RUNNER:browser;

<html>
  <body>
    <div id="my-element">Nothing inside 1...</div>
    <div id="my-element">Nothing inside 2...</div>
    <div id="my-element">Nothing inside 3...</div>
    <div id="my-element">Nothing inside 4...</div>
    <script>

	var handles = document.querySelectorAll( '#my-element' );

	for( var i = 0; i < handles.length; ++i )
		handles[ i ].innerHTML = 'Some <b>text</b> inside ' + ( i + 1 ) + '...';

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

Note: document.querySelectorAll works with duplicated ids but in practice you shouldn't use duplicated ids

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.