<p id="para">Some text here</p>
<button>blue</button>
<button>red</button>Document: getElementById() method / notebook
Document: getElementById() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
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());
});
});<div id="parent-id">
<p>hello word1</p>
<p id="test1">hello word2</p>
<p>hello word3</p>
<p>hello word4</p>
</div>const parentDOM = document.getElementById("parent-id");
const test1 = parentDOM.getElementById("test1");const element = document.createElement("div");
element.id = "test";
const el = document.getElementById("test"); // el will be null!