DOM Accessing

Methods to find and access DOM elements

🎯 Accessing DOM Elements

JavaScript provides multiple methods to find and access HTML elements in the DOM. Choosing the right method depends on your needs: unique IDs, class names, tag types, or complex CSS selectors for precise element targeting.


// Most common method
const element = document.getElementById('myId');
element.style.color = 'blue';
                                    

Access Methods

🆔

By ID

Find element by unique ID

getElementById('id')
📦

By Class

Find elements by class name

getElementsByClassName()
🏷️

By Tag

Find elements by tag name

getElementsByTagName()
🎨

By Selector

Find using CSS selectors

querySelector()
querySelectorAll()

🔹 getElementById()

The most efficient method to access a single element with a unique ID. Returns the element object or null if not found. IDs must be unique in a document, making this the fastest access method.

<div id="myDiv">Hello World</div>
<button onclick="changeText()">Change Text</button>

<script>
function changeText() {
  const element = document.getElementById('myDiv');
  element.innerHTML = 'Text changed!';
  element.style.color = 'blue';
}
</script>

Output (after click):

Text changed!

🔹 getElementsByClassName()

Returns a live HTMLCollection of all elements with the specified class name. The collection updates automatically when the DOM changes. Use array methods by converting to array or loop through with for...of.

<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<p class="text">Paragraph 3</p>
<button onclick="highlightAll()">Highlight All</button>

<script>
function highlightAll() {
  const elements = document.getElementsByClassName('text');
  
  // Loop through collection
  for(let i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = 'yellow';
  }
}
</script>

Output (after click):

Paragraph 1

Paragraph 2

Paragraph 3

🔹 getElementsByTagName()

Returns all elements with the specified tag name as a live HTMLCollection. Useful for selecting all paragraphs, divs, or any HTML element type. The collection reflects real-time changes to the document structure.

<p>First paragraph</p>
<p>Second paragraph</p>
<div>A div element</div>
<button onclick="styleParagraphs()">Style Paragraphs</button>

<script>
function styleParagraphs() {
  const paragraphs = document.getElementsByTagName('p');
  
  for(let p of paragraphs) {
    p.style.color = 'green';
    p.style.fontWeight = 'bold';
  }
}
</script>

Output (after click):

First paragraph

Second paragraph

A div element

🔹 querySelector()

Returns the first element matching a CSS selector. This modern method is very flexible, supporting any valid CSS selector including IDs, classes, attributes, pseudo-classes, and complex combinations for precise element selection.

<div class="container">
  <p class="text">First text</p>
  <p class="text highlight">Second text</p>
</div>
<button onclick="selectFirst()">Select First</button>

<script>
function selectFirst() {
  // Select first .text element
  const first = document.querySelector('.text');
  first.style.color = 'red';
  
  // Select element with multiple classes
  const highlighted = document.querySelector('.text.highlight');
  highlighted.style.fontStyle = 'italic';
}
</script>

Output (after click):

First text

Second text

🔹 querySelectorAll()

Returns a static NodeList of all elements matching the CSS selector. Unlike getElementsByClassName, this list doesn't update automatically. It's perfect for complex selections and works with modern array methods like forEach.

<ul>
  <li class="item">Item 1</li>
  <li class="item">Item 2</li>
  <li class="item">Item 3</li>
</ul>
<button onclick="styleItems()">Style Items</button>

<script>
function styleItems() {
  const items = document.querySelectorAll('.item');
  
  // Use forEach (works with NodeList)
  items.forEach((item, index) => {
    item.style.color = 'purple';
    item.textContent = `Item ${index + 1} - Updated`;
  });
}
</script>

Output (after click):

  • Item 1 - Updated
  • Item 2 - Updated
  • Item 3 - Updated

🔹 Advanced Selectors

querySelector and querySelectorAll support complex CSS selectors for precise element targeting. Combine multiple selectors, use attribute selectors, pseudo-classes, and descendant selectors to find exactly the elements you need in complex documents.

// Select by attribute
const input = document.querySelector('input[type="text"]');

// Select child elements
const firstChild = document.querySelector('.container > p:first-child');

// Select by multiple classes
const special = document.querySelector('.item.active.featured');

// Complex selector
const link = document.querySelector('nav ul li a[href="#home"]');

// Select all even paragraphs
const evenPs = document.querySelectorAll('p:nth-child(even)');

// Select elements with specific attribute
const required = document.querySelectorAll('input[required]');

Output:

✓ Elements selected using advanced CSS selectors

🔹 Choosing the Right Method

Select the appropriate method based on your specific needs for performance and functionality. getElementById is fastest for single elements, while querySelector offers maximum flexibility for complex selections in modern web applications.

Best Practices:

  • getElementById() - Best for single element with unique ID (fastest)
  • querySelector() - Best for complex CSS selectors (most flexible)
  • querySelectorAll() - Best for multiple elements with complex selection
  • getElementsByClassName() - Use when you need live collection
  • getElementsByTagName() - Use for all elements of specific type

🧠 Test Your Knowledge

Which method returns only the first matching element?