Accessing DOM Elements

The DOM model symbolizes a document through a coherent tree structure known as a node-tree. This structure comprises branches that culminate in nodes, each housing objects. Accessible via the tree, all nodes are subject to manipulation—content can be edited, removed, and new elements can be introduced. This hierarchical arrangement empowers developers to dynamically modify and enhance the document's content.

Document Object

The Document Object encapsulates the HTML document, delineating the constituent objects or nodes forming the document's structure, along with the interfaces that empower scripts and programs to interact with and modify these document objects. It furnishes developers with a standardized approach to depict all elements within a webpage, ensuring uniform accessibility through a shared repertoire of properties and methods. This unifying framework simplifies the process of retrieving and manipulating the contents of a web page, thereby streamlining web development tasks.

DOM Methods

The prevalent technique for selecting an element involves utilizing the document.getElementById method. Within an HTML document, each element can possess an optional ID attribute, which necessitates uniqueness. This method requires an ID string as input and furnishes a reference to the element bearing the specified ID; if no such element exists, it returns null. Historically, the DOM standard introduced two fundamental methods for element retrieval: getElementById() and getElementsByTagName(). In tandem, the HTML5 specification introduces three supplementary methods: getElementsByClassName(), querySelector(), and querySelectorAll(), further enhancing the array of techniques available for accessing elements.

  1. getElementById() - Finding by ID
  2. getElementsByClassName()- Finding by Class
  3. getElementsByTagName() - Finding by Tag
  4. querySelector() - Finding by Selector (single)
  5. querySelectorAll() - Finding by Selector (all)

getElementById()

JavaScript offers the document.getElementById() method as a straightforward means to retrieve an element within the DOM's hierarchical structure. This method facilitates access to an element by using its unique ID attribute value. By calling this method and supplying the desired ID, developers can seamlessly pinpoint and obtain the specific element they seek from the DOM tree.

document.getElementById('heading')
run this source code Browser View

Document Object Model

Source
<html> <body> <h1 id="heading">Access this text....</h1> <button onclick="changeIt()">Get Value</button> <script> function changeIt() { var title_element = document.getElementById('heading').innerHTML; alert(title_element); } </script> </body> </html>

getElementsByTagName()

The getElementsByTagName() method retrieves a collection of child elements belonging to a specific parent element, identified by the specified tag name. This collection is encapsulated as a NodeList object, facilitating convenient traversal and manipulation of the retrieved elements.

run this source code Browser View

Paragraph 1

Paragraph 2

Source
<html> <body> <p>Paragraph 1</p> <p>Paragraph 2</p> <button onclick="count()">Get Value</button> <script> function count() { var cnt = document.getElementsByTagName("p"); alert(cnt.length); } </script> </body> </html>

getElementsByClassName()

The getElementsByClassName() function furnishes an object akin to an array, encompassing all child elements that possess all of the specified class names. This method acts as a convenient means to gather elements based on their assigned classes, streamlining the process of handling elements with specific styling or functionality requirements.

document.getElementsByClassName("ClassName");
run this source code Browser View

Paragraph 1

Paragraph 2

Source
<html> <body> <p class="testClass">Paragraph 1</p> <p class="testClass">Paragraph 2</p> <button onclick="count()">Change Value</button> <script> function count() { var tmpClass = document.getElementsByClassName("testClass"); alert(tmpClass.length); tmpClass[0].innerHTML ="First Paragraph changed !!"; } </script> </body> </html>

The above program first alert 2, the number of p elements, and then it change the first p element's text to "First Paragraph changed !!".

Contemporary web browsers incorporate APIs known as querySelector() and querySelectorAll(), designed to locate one or multiple elements that correspond to a given CSS selector. These methods enable querying of an HTML document to identify DOM elements that adhere to the specified CSS selector. By offering inherent support for selector-based queries, these browser-integrated capabilities have contributed to the popularity of JavaScript libraries that offered similar functionality in the past.

querySelector() example

The querySelector() function retrieves the initial element within the document that aligns with the provided group of selectors. In cases where no matches are detected, the function returns null. This method's primary purpose is to facilitate the targeted selection of elements based on specified criteria, providing enhanced precision when working with complex or specific DOM structures.

run this source code Browser View

Paragraph 1

Paragraph 2

Source
<html> <body> <p id="qSelector">Paragraph 1</p> <p id="qSelector1">Paragraph 2</p> <button onclick="change()">Change Value</button> <script> function change() { document.querySelector("#qSelector").innerHTML ="First Paragraph"; } </script> </body> </html>

querySelectorAll() example

The querySelectorAll() function yields a list comprising elements that correspond to the provided group of selectors, arranged in the order they appear within the source. Notably, this collection remains static, impervious to any subsequent alterations made to the document. This characteristic ensures that changes enacted within the document do not influence the elements contained within the collection, thereby preserving the integrity and consistency of selected elements.

run this source code Browser View
div content 1

Paragraph 2

Source
<html> <body> <div class="div_">div content 1</div> <p class="p_">Paragraph 2</p> <button onclick="change()">Change Value</button> <script> function change() { var elements = document.querySelectorAll(".div_,.p_"); elements[0].innerHTML = "div content changed"; elements[1].innerHTML = "Paragraph changed"; } </script> </body> </html>

Conclusion

Accessing DOM elements in JavaScript can be achieved through methods like getElementById(), getElementsByTagName(), getElementsByClassName(), querySelector(), and querySelectorAll(). These methods empower developers to single out specific elements based on IDs, tag names, classes, or CSS selectors. This accessibility enhances web development by simplifying the process of manipulating and interacting with elements within the document.