Another useful search techniques in JavaScript

You already know the querySelector and querySelectorAll methods for finding elements on a page. These convenience methods are relatively recent additions to JavaScript. There are other methods that you may come across and apply if necessary. Let's take a look at them.

Getting by id

Given the element #elem:

<div id="elem"></div>

Get this element using the getElementById method and set some text to it.

Getting by tag name

Given a list:

<ul> <li>text</li> <li>text</li> <li>text</li> <li>text</li> <li>text</li> </ul>

Get all the li tags by tag name and make their text red.

Getting by class name

Given the elements:

<p class="www">elem 1</p> <p class="www">elem 2</p> <p class="www">elem 3</p>

Get these elements by class name and make their text red.

enru