JavaScript Find/Get Element

May 26, 2019
Using getElementsBy or querySelector

By Id

<div id="my-title">My Title</div>
const titleEl = document.getElementById('my-title');

or

const titleEl = document.querySelector('#my-title');

NOTE: Check querySelector browser support or can i use querySelector.

Get the text of element

console.log(titleEl.text);

By Class

<div class="row">Row 1</div><div class="row">Row 2</div>
const rows = document.getElementsByClassName('row');

or

const rows = document.querySelector('.row');

Loop through all elements

rows.forEach(el => {  console.log(el.text);});

By Tag

<article>Article 1</article><article>Article 2</article>
const articles = document.getElementsByTagName('article');

or

const articles = document.querySelector('article');

Loop through all elements

articles.forEach(el => {  console.log(el.text);});

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.