document.getElementsByClassName("test");Document: getElementsByClassName() method / notebook
Document: getElementsByClassName() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
document.getElementsByClassName("red test");document.getElementById("main").getElementsByClassName("test");document.getElementsByClassName("test")[0];const testElements = document.getElementsByClassName("test");
const testDivs = Array.prototype.filter.call(
testElements,
(testElement) => testElement.nodeName === "DIV",
);<div id="parent-id">
<p>hello world 1</p>
<p class="test">hello world 2</p>
<p>hello world 3</p>
<p>hello world 4</p>
</div>const parentDOM = document.getElementById("parent-id");
const test = parentDOM.getElementsByClassName("test"); // a list of matching elements, *not* the element itself
console.log(test); // HTMLCollection[1]
const testTarget = parentDOM.getElementsByClassName("test")[0]; // the first element, as we wanted
console.log(testTarget); // <p class="test">hello world 2</p><span class="orange fruit">Orange Fruit</span>
<span class="orange juice">Orange Juice</span>
<span class="apple juice">Apple Juice</span>
<span class="foo bar">Something Random</span>
<textarea id="resultArea"></textarea>