JavaScript JS Tutorial JS Objects JS Functions JS Classes JS Async JS HTML DOM JS Browser BOM JS Web APIs JS AJAX JS JSON JS vs jQuery JS Graphics



DOM Collections

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can interact with the page.

DOM Collections are arrays of DOM elements that can be accessed and manipulated using JavaScript. They are used to group together similar elements on a web page, such as all the links or all the images. DOM Collections are created using various methods, such as getElementsByTagName(), getElementsByClassName(), and querySelectorAll().

The getElementsByTagName() method returns a collection of all the elements with the specified tag name. For example, the following code will return a collection of all the <p> elements on the page:

<script>
  var paragraphs = document.getElementsByTagName("p");
</script>

The getElementsByClassName() method returns a collection of all the elements with the specified class name. For example, the following code will return a collection of all the elements with the class name "example":

<script>
  var examples = document.getElementsByClassName("example");
</script>

The querySelectorAll() method returns a collection of all the elements that match the specified CSS selector. For example, the following code will return a collection of all the elements with the class name "example" that are inside a <div> element:

<script>
  var examples = document.querySelectorAll("div .example");
</script>

Once you have a DOM Collection, you can access and manipulate its elements using JavaScript. For example, the following code will change the text of all the <p> elements on the page:

<script>
  var paragraphs = document.getElementsByTagName("p");
  for (var i = 0; i < paragraphs.length; i++) {
    paragraphs[i].innerHTML = "New text!";
  }
</script>

DOM Collections are a powerful tool for web developers. They allow you to group together similar elements on a web page and manipulate them using JavaScript. By using DOM Collections, you can create dynamic and interactive web pages that respond to user input.

References

Activity