Technology Apr 28, 2026 · 1 min read

DOM

What is getElementById()? It is used to select a single HTML element using its unique id attribute. Returns an Element object if a match is found; otherwise, it returns null. <h1 id="title">Hello</h1> let el = document.getElementById("title"); console.log(el); Output :...

DE
DEV Community
by Nanthini Ammu
DOM

What is getElementById()?

  • It is used to select a single HTML element using its unique id attribute.
  • Returns an Element object if a match is found; otherwise, it returns null.
<h1 id="title">Hello</h1>
let el = document.getElementById("title");
console.log(el);

Output :
<h1 id="title">Hello</h1>

Changing content :

el.textContent = "Hello, JavaScript!"; 
el.innerText = "Hi!"; 
el.innerHTML = "<b>How</b>";

Changing Style :

el.style.color ="red";
el.style.backgroundColor ="yellow";
document.body.style.backgroundColor = "black";

Adding Event :

<body>

<h1 id="title">Hello</h1>
<button id="btn">click</button>

<script>

let el = document.getElementById("title");     
let btn = document.getElementById("btn");     
btn.addEventListener("click", () => {
el.innerText ="Wecome!";
});

</script>
</body>
DE
Source

This article was originally published by DEV Community and written by Nanthini Ammu.

Read original article on DEV Community
Back to Discover

Reading List