ELEMENT SELECTORS IN DOM:
Element Selector:
JavaScript element selectors are built-in DOM methods used to target, select, and manipulate HTML elements on a webpage.
Finding HTML elements by id
Finding HTML elements by tag name
Finding HTML elements by class name
Finding HTML elements by CSS selectors
Finding HTML elements by HTML object collections
Id selector:
1. document.getElementById():
- Finds a single unique element by its strict id attribute.
Example:
const header = document.getElementById("head");
<h1 id="main" >keerthana</h1>
<script>
const element= document.getElementById("main");
console.log(element.innerText);
</script>
OUTPUT:
keerthana
class selector:
2. document.getElementsByClassName():
- Finds all elements sharing a specific class attribute.
Example:
const buttons = document.getElementsByClassName("btn");
<h1 class="main" >hello sir</h1>
<script>
const element1= document.getElementsByClassName("main");
console.log(element1[0].innerText);
</script>
OUTPUT:
hello sir
Tag selector:
3. document.getElementsByTagName():
- Finds all elements matching a specific HTML tag.
Example:
const paragraphs = document.getElementsByTagName('p');
<h1>keerthana</h1>
<script>
const tag= document.getElementsByTagName("h1");
console.log(tag[0].innerText);
</script>
OUTPUT:
Keerthana
Queryselector:
4. document.querySelector():
- Finds the first element that matches the specified CSS selector.
Example:
const mainNav = document.querySelector('#nav');
<h1 class="main" >hello world</h1>
<script>
const query= document.querySelector(".main");
console.log(query.innerText);
</script>
OUTPUT:
hello world
QueryselectorAll:
5. document.querySelectorAll():
- Finds all elements that match the specified CSS selector.
Example:
const cards = document.querySelectorAll('.card');
<h2 class="main" >hello</h2>
<script>
const queryAll= document.querySelectorAll("h2");
console.log(queryAll[0].innerText);
</script>
OUTPUT:
hello
Top comments (0)