Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

JavaScript - get element handle by id

0 contributions
9 points

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

0 contributions

Suggested wiki articles:

Suggested findings

Let's do the work and have some fun
  • Dirask is online IT community for professionals and hobbyist 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,
    we will help you. 👍 ✔ 🦄
Read more