Logo

Developer learning path

JavaScript

Accessing HTML elements with JavaScript

Accessing HTML elements with JavaScript

42

#description

Accessing HTML elements with JavaScript allows you to manipulate and interact with the content on a webpage dynamically. You can use JavaScript code to select the desired HTML elements and modify their content, attributes, styles or behavior.

To access an HTML element with JavaScript, you first need to identify it by its tag name, class name, ID, attribute value or other selector. The simplest way to select an element is by its ID, which must be unique within the page.

You can use the document.getElementById() method to select the element and store it in a variable:

                    
let myElement = document.getElementById("elementID");
                  

Once you have the element reference, you can access and modify its properties and methods.

For example, you can change the text inside a paragraph element using the innerHTML property:

                    
myElement.innerHTML = "New text here";
                  

You can also add or remove classes from an element using the className property or the classList property, which has methods like add(), remove() and toggle():

                    
myElement.classList.add("active");
                  

Other useful methods for accessing HTML elements with JavaScript include getElementsByTagName(), getElementsByClassName(), querySelector(), and querySelectorAll(). These methods allow you to select one or multiple elements based on their tag name, class name, or CSS selector.

Overall, accessing HTML elements with JavaScript is a powerful technique that unlocks many possibilities for creating interactive and dynamic web pages.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.