Nearby lessons
2 of 14JavaScript DOM Targeting Methods
📌 What are DOM Targeting Methods?
If you want to change or access parts of your webpage using JavaScript, you need to target HTML elements first. JavaScript gives us powerful DOM (Document Object Model) methods to select elements by their id, class, or tag name. Once selected, we can change their content, style, or add interactivity.
🔍 getElementById()
getElementById() is one of the most commonly used methods to select a single element by its unique ID. If there's no element with the given ID, it returns null.
Syntax: document.getElementById("element_ID")
📦 getElementsByClassName()
getElementsByClassName() returns all elements with a specific class name as an HTMLCollection. You can access individual elements using index numbers like an array.
Syntax: document.getElementsByClassName("className")
🔖 getElementsByTagName()
getElementsByTagName() returns all elements with a given tag name (like <p>, <div>, <h1>) as an HTMLCollection. Great for selecting multiple similar elements at once.
Syntax: document.getElementsByTagName("tagName")
✍️ innerText
innerText allows you to get or change the text content of an HTML element. It only includes the visible text (ignores hidden content or HTML tags).
Syntax: element.innerText = "New text";
📝 innerHTML
innerHTML lets you get or update the HTML content inside an element. You can add tags like <b>, <span>, and more.
Syntax: element.innerHTML = "<b>Bold Text</b>";
📘 Common DOM Selection & Manipulation Methods Table
| Attribute | Description |
|---|---|
🔍 getElementById() | Selects a single element using its unique ID. Returns null if not found. |
📦 getElementsByClassName() | Returns a live HTMLCollection of all elements with a specific class name. |
🔖 getElementsByTagName() | Returns all elements with a specific tag name (like p, div, h1). |
✍️ innerText | Sets or gets the visible text inside an element (ignores HTML). |
📝 innerHTML | Sets or gets the full HTML content inside an element. |
🧭 querySelector() | Selects the first element that matches a CSS selector. |
📚 querySelectorAll() | Selects all elements that match a CSS selector and returns a NodeList. |