Do We Still Need to Use document.getElementById Anymore

One of the notorious lines of code is the "document.getElementById" in JavaScript. because this line will appear again and again, and even with copy and paste, you still need a declare a DOM element and change the element id. This is a lot of work.

I guess this is one reason why jQuery has been famous for. You just need to write var xyz = $(#someid) which is fairly short.

But now with most browsers support ES7 now and one new feature is that we no longer need to declare the element anymore. We can just call the element in JavaScript by its id.

Playground

Sample Code

The above app has the following code:
<input id = "input20220107">
<div id = "app"> 
</div>
<script>
  input20220107.addEventListener("input", () => app.innerHTML = input20220107.value); 
</script>
The automatic call for the document.getElementById feature also works for inline JavaScript like this one, Type in the input box below.
<input oninput="showsomething.innerHTML = this.value" />
<div id="showsomething"></div>

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser