Introducing querySelector and querySelectorAll

0
2263

Comparing with getElementById, getElementByName,… querySelector and querySelectorAll are newcomers but soon become popular regarding their conveniences and consistent of using.

How to use querySelector and querySelectorAll?

With querySelector we can use the same selector notation with CSS, as it makes thing more consistent when working with CSS and DOM, the two that are essential knowledge for web developing.

document.querySelector('body') // select the body tag
document.querySelector('#id1') // select an element that have id="id1"
document.querySelectorAll('.class1') //select all element that have class="class1"
document.querySelectorAll("input[type='text']") //select all input element have type="text"

Using querySelector:

querySelector returns the only or the first element that is selected. It’s usually used to select an element by id since it should be used uniquely for a specific element in your whole HTML file.

In case that you use querySelector to select element by tag name, class,… it will return the first element in the list.

document.querySelector('#id1') // return the only element that have id="id1" 
document.querySelector('.class1') // return the first element have class name of ".class1"

Using querySelectorAll:

querySelectorAll returns a list of elements that have the same tag name, class name,… that you put in as the parameter. Even if you pass in an id, it still returns a list with a single element inside.

document.querySelectorAll('body')[0].style.backgroundColor = 'red'
//access the style property of body tag then change background color to red.

As far as we know, there’s only one body tag in HTML document, but if we select it using querySelectorAll, we still need to provide an index. The list that is returned in the code above is a list with a single element, therefore, the index of that element must be 0.

Since querySelectorAll returns a list which is similar to the array, we can use the index or for loop to access the element.

var requiredInput = document.querySelectorAll("input[type='text']");

for (var i = 0; i < requiredInput.length; i++) {
 if (requiredInput[i].value === '') alert("This field can't be empty")
 }

Hope this post provides you enough interest to use querySelector and querySelectorAll next time you work on DOM manipulation.

LEAVE A REPLY

Please enter your comment!
Please enter your name here