Javascript list all html elements

How to get DOM elements using JavaScript

The Document Object Model (DOM) is a programming interface for HTML and XML documents created by the browser once the document is loaded. A web page is a document represented by the DOM as nodes and objects. It allows programs to manipulate the document’s content, structure, and styles.

In this tutorial, we shall learn how to use JavaScript to access different nodes (HTML elements) in the DOM. Let us start with the first method: getting an element by ID.

The document ‘s getElementById() method takes the element ID as input and returns an Element object representing the DOM element. Here is an example:

const unicorn = document.getElementById('unicorn') 

The ID is case-sensitive and unique across the entire HTML document. So this method always returns a single element. If no matching element is found, it returns null .

Note: Do not put the # sign before the ID string while calling getElementById() method. You will get null instead of the element, and then you might wonder for hours what has gone wrong.

The getElementsByTagName() method is used to access multiple elements. It takes the tag name as input and returns all of the DOM elements that match the tag name as HTMLCollection :

Читайте также:  Centos java 7 jre

JavaScript code to access all

elements:

const animals = document.getElementsByTagName('p') 

This method searches only one tag name at a time. But if you pass in * as the tag name, you will get all elements in the DOM:

const allNodes = document.getElementsByTagName('*') 

The getElementsByName() method is used to get a collection of elements by their name attribute and returns a NodeList object:

input type="text" name="email"> input type="tel" name="phone"> input type="date" name="dob"> 
const emails = document.getElementsByName('email') 

Note: Unlike the id attribute, which must be unique, multiple HTML elements can have the same name attribute. That’s why getElementsByName() returns a collection of nodes.

Want to use the class attribute to get a list of matching elements? You can use the getElementsByClassName() method, pass it a class name (without . ), and it will return an HTMLCollection of all DOM elements that have the given class name:

div class="bird owl">🦉div> div class="bird">🐦div> div class="bird eagle">🦅div> div class="animal cat">🐱div> 
const birds = document.getElementsByClassName('bird') 

This method also accepts multiple class names separated by spaces. Let us get all elements that have both the bird and eagle classes:

const eagle = document.getElementsByClassName('bird eagle') 

The querySelector() method is one of the two modern JavaScript methods that allow you to get elements from DOM based on CSS selectors. Just pass in the CSS selector, and you will get the first element that matches the specified selector. If no matches exist, it returns null . Here is an example:

const email = document.querySelector('#signup input[name="email"]') 

Want to select a list of elements that match the specified selectors? Use the querySelectorAll() method instead. This method takes multiple CSS selectors as input and returns a NodeList , a list of DOM elements that match the given selectors. Let us select all elements with a class of either bird or animal from the above HTML markup:

const elems = document.querySelectorAll('.bird, .animal') console.log(elems.length) // 4 

You can also chain multiple functions together to search elements within another element. You first need to select a single element using either getElementById() or querySelector() and then chain another function to search within:

form id="signup"> input type="text" name="email"> input type="tel" name="phone"> input type="date" name="date-of-birth"> form> 
const inputs = document.getElementById('signup').getElementsByTagName('input') // OR const inputs = document.querySelector('#signup').querySelectorAll('input') 

Most of the methods we discussed above (except getElementById() and querySelector() ) returns multiple elements as either an HTMLCollection or a NodeList . The HTMLCollection is not an array but a generic collection of elements. So it is impossible to iterate over it with the forEach() or map() method. However, we can convert it to a real array and then iterate using the Array.from() method:

const inputs = document.getElementById('signup').getElementsByTagName('input') // iterate over HTMLCollection Array.from(inputs).forEach(element =>  console.log(element) >) 

Although NodeList is also not an array, it does provide the forEach() method to iterate over the elements:

const inputs = document.querySelector('#signup').querySelectorAll('input') //iterate over NodeList inputs.forEach(element =>  console.log(element) >) 

That’s all for getting DOM elements using JavaScript. We have learned about many different methods to access the DOM elements: using the id attribute, HTML tag name, name attribute, class attribute, and CSS selectors. We also discussed ways to iterate over the generic collection of elements returned by these methods. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

JavaScript querySelectorAll with Examples

In this tutorial, you will learn about javascript querySelectorAll, how this method can help to select any element or a group of elements from the DOM with examples.

As a web developer, you may come across many situations when you need to select a group of elements from DOM that shares similar properties like the same element or same class.

In such cases, there could no better choice than the querySelectorAll method. It can select a whole lot of elements from the DOM having some similar properties.

querySelectorAll JavaScript

Following is the list of things we are going to see in this tutorial.

Introduction To JavaScript querySelectorAll method

The JavaScript querySelectorAll method is used to select elements in the document using CSS selectors and returns all the matching elements as a list.

The method returns a static NodeList (an array-like object) that contains a list of all elements that match the specified selectors or group of selectors.

document.querySelectorAll(selectors); // or parent.querySelectorAll(selectors);

The selectors parameter is a string that specifies the selectors to match.

You can call the querySelectorAll method directly on the document or on any other HTML element (parent).

    The method applied on the document — When applied on a document it will select all elements within the document that matches the query.

 
Paragraph in container 1

Paragraph in container 2

Paragraph in container 3

Paragraph in container 4

Outer paragraph 1

Outer paragraph 2

Outer paragraph 3

Outer paragraph 4

output 1

 
Paragraph in container 1

Paragraph in container 2

Paragraph in container 3

Paragraph in container 4

Outer paragraph 1

Outer paragraph 2

Outer paragraph 3

Outer paragraph 4

output 2

Note : If the specified selector is a CSS pseudo-element then the method returns an empty list.

A universal selector to select all elements

The universal selector (*) selects all the elements of the document including , , , and other elements of .

Example — Universal selector

// Select all the elements in the document var all = document.querySelectorAll('*'); console.log(all);

Select elements by tag name

To select elements by tag name, you can pass the tag name as a parameter to the querySelectorAll method. If you apply the method on the document, then it will select all the elements of the specified tag name within the document and if you apply it on any element then it will select all the elements of the specified tag name within the specified element.

Look at the following. Select all the Nodelist of

elements in the DOM:

let paragraphs = document.querySelectorAll("p")

To select all the Nodelist of elements (images) in the DOM:

let images = document.querySelectorAll("img")

Select All Elements By Class

To select all elements of a class pass the class name preceding with a dot(.) as an argument in the querySelectorAll method. It will return all elements of the specified class within the document or in the parent element.

Since the method returns an array-like object which is a list of all matched elements, to access the element you have to loop through the list using for loop or forEach loop.

 

Select elements

Output :
Used both for loop and forEach loop to access the elements of the list.

output 3

Getting a list of matches

The querySelectorAll method returns all the matches of the list of matching elements.

The example below returns all the elements within the document having class either of box or container .

let elements = document.querySelectorAll(".box, .container"); // loop through all the elements elements.forEach(element => < element.style.background = "lightgreen"; >);

Output :
The method returns all the elements having either of 2 classes as a Nodelist.

output 4

Select elements by attribute

To select an element by the attribute pass the attribute name in the method by wrapping it in a square bracket. Example [title] .

let elements = document.querySelectorAll("[title]"); // loop through all the elements elements.forEach(element => < element.style.background = "lightgreen"; >);

Let’s now select all the paragraph that has a title attribute. In the following example select all the paragraph elements with the attribute [title] with any value.

let elements = document.querySelectorAll("p[title]");

Getting all elements with the same attribute value

Pass the attribute with its value as a selector in the method. Like to select all anchor elements whose href value is https://www.tutorialstonight.com , the code would be as follows:

let elements = document.querySelectorAll("a[href='https://www.tutorialstonight.com']")

Combining selectors to select a group of elements

Suppose there is a container having multiple lists of items and you have to select 1st list element of all the lists using javascript. You can achieve it by the querySelectorAll method.

Let the HTML code of the lists be as follows and the first element of all the lists is to be selected.

  • List number 1. Item Number 01.
  • List number 1. Item Number 02.
  • List number 1. Item Number 03.
  • List number 1. Item Number 04.
  • List number 1. Item Number 05.
  • List number 2. Item Number 01.
  • List number 2. Item Number 02.
  • List number 2. Item Number 03.
  • List number 2. Item Number 04.
  • List number 2. Item Number 05.
  • List number 3. Item Number 01.
  • List number 3. Item Number 02.
  • List number 3. Item Number 03.
  • List number 3. Item Number 04.
  • List number 3. Item Number 05.

Use combinator selectors to grab the desired elements.

let elements = document.querySelectorAll(".container ul li:nth-child(1)"); // loop through all the elements elements.forEach(element => < element.style.background = "lightgreen"; >);

output 5

Special Case

The querySelectorAll method behaves differently than other JavaScript DOM libraries.

Conside the example below:

  

When you select inner class on .middle element with query of «.outer .inner» then it returns .inner element even though .outer is not a descendant (child) of .middle class element.

By default, the querySelectorAll method only varifies the last element in the selector within the search scope.

To restore the expected behavior use :scope pseudo-class with it.

let middle = document.querySelector(".middle"); let elements = middle.querySelectorAll(":scope .outer .inner"); console.log(elements); // return blank nodelist

Conclusion

In this section, we learned about the JavaScript querySelectorAll method, it’s used and worked with multiple examples and selecting all kinds of queries with both simple and complex selectors.

Источник

Оцените статью