MDN self-hosted library · e01.org

Document: getElementById() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<p id="para">Some text here</p>
<button>blue</button>
<button>red</button>
js
function changeColor(newColor) {
  const elem = document.getElementById("para");
  elem.style.color = newColor;
}

document.querySelectorAll("button").forEach((button) => {
  button.addEventListener("click", (event) => {
    changeColor(event.target.textContent.toLowerCase());
  });
});
html
<div id="parent-id">
  <p>hello word1</p>
  <p id="test1">hello word2</p>
  <p>hello word3</p>
  <p>hello word4</p>
</div>
js
const parentDOM = document.getElementById("parent-id");
const test1 = parentDOM.getElementById("test1");
js
const element = document.createElement("div");
element.id = "test";
const el = document.getElementById("test"); // el will be null!