Languages
[Edit]
EN

JavaScript - get element handle by id

10 points
Created by:
JustMike
26150

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

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join