DOM (Document Object Model) selectors are methods provided by the browser to access elements in an HTML document. Here are the primary types of DOM selectors explained with examples:
1. getElementById
This method selects an element by its unique id attribute.
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<div id="myDiv">Hello, World!</div>
<script>
var element = document.getElementById('myDiv');
console.log(element.textContent); // Output: Hello, World!
</script>
</body>
</html>
2. getElementsByClassName
This method selects all elements with a specified class name and returns an HTMLCollection (similar to an array, but not exactly).
<!DOCTYPE html>
<html>
<head>
<title>getElementsByClassName Example</title>
</head>
<body>
<div class="myClass">Element 1</div>
<div class="myClass">Element 2</div>
<div class="myClass">Element 3</div>
<script>
var elements = document.getElementsByClassName('myClass');
console.log(elements.length); // Output: 3
</script>
</body>
</html>
3. getElementsByTagName
This method selects all elements with the specified tag name.
<!DOCTYPE html>
<html>
<head>
<title>getElementsByTagName Example</title>
</head>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<script>
var elements = document.getElementsByTagName('p');
console.log(elements.length); // Output: 3
</script>
</body>
</html>
4. querySelector
This method returns the first element that matches a specified CSS selector.
<!DOCTYPE html>
<html>
<head>
<title>querySelector Example</title>
</head>
<body>
<div class="myClass">Element 1</div>
<div class="myClass">Element 2</div>
<script>
var element = document.querySelector('.myClass');
console.log(element.textContent); // Output: Element 1
</script>
</body>
</html>
5. querySelectorAll
This method returns all elements that match a specified CSS selector as a NodeList (similar to an array).
<!DOCTYPE html>
<html>
<head>
<title>querySelectorAll Example</title>
</head>
<body>
<div class="myClass">Element 1</div>
<div class="myClass">Element 2</div>
<div class="myClass">Element 3</div>
<script>
var elements = document.querySelectorAll('.myClass');
elements.forEach(function(element) {
console.log(element.textContent);
});
// Output:
// Element 1
// Element 2
// Element 3
</script>
</body>
</html>
Summary
getElementById: Selects a single element by its id.
getElementsByClassName: Selects all elements with a specified class name.
getElementsByTagName: Selects all elements with a specified tag name.
querySelector: Selects the first element that matches a CSS selector.
querySelectorAll: Selects all elements that match a CSS selector.
These methods are fundamental for interacting with the DOM, allowing you to dynamically update content, handle events, and manipulate the structure of your web pages.
Top comments (0)