MDN self-hosted library · e01.org

Document: getElementsByClassName() method

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

js
document.getElementsByClassName("test");
js
document.getElementsByClassName("red test");
js
document.getElementById("main").getElementsByClassName("test");
js
document.getElementsByClassName("test")[0];
js
const testElements = document.getElementsByClassName("test");
const testDivs = Array.prototype.filter.call(
  testElements,
  (testElement) => testElement.nodeName === "DIV",
);
html
<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>
js
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>
html
<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>