Languages
[Edit]
EN

JavaScript - get element handle by id

10 points
Created by:
Rubi-Reyna
677

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. using 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. using 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. using 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:

The document.querySelectorAll works with duplicated ids but in practice, you shouldn't use duplicated ids

Alternative titles

  1. JavaScript - getting element handle with getElementById, querySelector and querySelectorAll
  2. JavaScript - get HTML element handle by id
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join