Using the querySelector method

The querySelector method returns an element in the same way as when selecting an element through its CSS selector. However, document.querySelector returns only one element. Therefore, we can operate on it directly once we query for that element:

<div data-attr="coolDIV">Make me red!</div><script>document.querySelector('div[data-attr]').style.color = 'red'; // div becomes red</script>

It is equivalent to doing document.querySelector('div').style.color = 'red'; if we have only one <div> tag in the body.

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.