πŸ—£ In this post you will get familiar with JavaScript elements! Learn how to get, change, and manipulate HTML elements, styles, and more. πŸš€

πŸ†” Getting Elements by ID

One of the most common ways to access HTML elements in JavaScript is by using the getElementById() method. This method allows you to get an element by its unique ID.

Example:

let element = document.getElementById("myElement");
element.innerHTML = "New content here!";

✏️ Changing HTML Content

You can modify the innerHTML property of an element to change its content dynamically.

Example:

document.getElementById("header").innerHTML = "Updated Header Text!";

🎨 Changing Styling

JavaScript allows you to change the style of an HTML element dynamically by accessing its style property.

Example:

document.getElementById("myElement").style.color = "blue";
document.getElementById("myElement").style.fontSize = "20px";

🏷️ Accessing and Changing the Classes of an Element

You can use the classList property to add, remove, or toggle classes on an element.

Example:

let element = document.getElementById("myElement");
element.classList.add("new-class");
element.classList.remove("old-class");

πŸ”§ Getting and Setting HTML Attributes

To get or set HTML attributes such as src, href, or alt, you can use getAttribute() and setAttribute() methods.

Example:

let image = document.getElementById("myImage");
let src = image.getAttribute("src");
image.setAttribute("src", "new-image.jpg");

🏷️ Getting Elements by Class or Tag Name

If you want to retrieve elements by their class name or tag name, you can use getElementsByClassName() and getElementsByTagName() methods.

Example (By Class Name):

let elements = document.getElementsByClassName("myClass");
elements[0].style.backgroundColor = "yellow";

Example (By Tag Name):

let paragraphs = document.getElementsByTagName("p");
paragraphs[0].style.fontWeight = "bold";

πŸ” Making Queries with Selectors

For more flexible element selection, you can use querySelector() (for a single element) or querySelectorAll() (for multiple elements) to select elements based on CSS selectors.

Example (Single Element):

let div = document.querySelector(".myDiv");
div.style.color = "green";

Example (Multiple Elements):

let buttons = document.querySelectorAll("button");
buttons.forEach(button => button.style.border = "2px solid black");

πŸ”„ Navigating DOM Relationships

JavaScript provides various ways to navigate the DOM relationships of elements, such as using parentNode, childNodes, previousElementSibling, and nextElementSibling.

Example:

let firstChild = document.getElementById("parentElement").firstElementChild;
let nextSibling = firstChild.nextElementSibling;

βž•βž– Adding and Removing Elements

You can dynamically add or remove elements in the DOM using methods like appendChild(), removeChild(), and insertBefore().

Example (Add an Element):

let newDiv = document.createElement("div");
newDiv.innerHTML = "New dynamically added element";
document.body.appendChild(newDiv);

Example (Remove an Element):

let elementToRemove = document.getElementById("removeMe");
document.body.removeChild(elementToRemove);

πŸ“œ Complete List of JavaScript Elements

Here’s a quick list of common JavaScript methods and properties for working with HTML elements:

  • getElementById() – Get an element by ID.
    Example:
    <div id="myElement">Old content</div>
    <script>
    let element = document.getElementById("myElement");
    element.innerHTML = "New content here!";
    // Result: The content of the element with ID "myElement" will change to "New content here!"
    </script>

  • getElementsByClassName() – Get elements by class name.
    Example:
    <div class="myClass">First element</div>
    <div class="myClass">Second element</div>
    <script>
    let elements = document.getElementsByClassName("myClass");
    elements[0].style.color = "red";
    // Result: The first element with class "myClass" will turn red.
    </script>

  • getElementsByTagName() – Get elements by tag name.
    Example:
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <script>
    let paragraphs = document.getElementsByTagName("p");
    paragraphs[1].style.fontWeight = "bold";
    // Result: The second paragraph will turn bold.
    </script>

  • querySelector() – Get the first element matching a CSS selector.
    Example:
    <div class="myDiv">Content here</div>
    <script>
    let div = document.querySelector(".myDiv");
    div.style.backgroundColor = "yellow";
    // Result: The div background will turn yellow.
    </script>

  • querySelectorAll() – Get all elements matching a CSS selector.
    Example:
    <button>Button 1</button>
    <button>Button 2</button>
    <script>
    let buttons = document.querySelectorAll("button");
    buttons.forEach(button => button.style.border = "2px solid black");
    // Result: All buttons will have a 2px solid black border.
    </script>

  • innerHTML – Get or set the HTML content inside an element.
    Example:
    <div id="header">Original Text</div>
    <script>
    document.getElementById("header").innerHTML = "Updated Text!";
    // Result: The content of the div with ID "header" will change to "Updated Text!".
    </script>

  • classList – Get or modify the classes of an element.
    Example:
    <div id="myElement">Text inside element</div>
    <script>
    document.getElementById("myElement").classList.add("new-class");
    document.getElementById("myElement").style.color = "green";
    // Result: The element will have the "new-class" class and turn green.
    </script>

  • style – Get or set the inline styles of an element.
    Example:
    <div id="myElement">Change my style</div>
    <script>
    document.getElementById("myElement").style.backgroundColor = "blue";
    // Result: The background color of the element will turn blue.
    </script>

  • getAttribute() – Get the value of an attribute.
    Example:
    <img id="myImage" src="old-image.jpg" alt="Image">
    <script>
    let image = document.getElementById("myImage");
    let src = image.getAttribute("src");
    image.setAttribute("src", "new-image.jpg");
    // Result: The "src" attribute of the image will change to "new-image.jpg".
    </script>

  • setAttribute() – Set the value of an attribute.
    Example:
    <img id="myImage" src="old-image.jpg" alt="Image">
    <script>
    document.getElementById("myImage").setAttribute("alt", "New image description");
    // Result: The "alt" attribute of the image will change to "New image description".
    </script>

  • appendChild() – Add a new child element to an element.
    Example:
    <div id="parentElement"></div>
    <script>
    let newDiv = document.createElement("div");
    newDiv.innerHTML = "New dynamically added element";
    document.getElementById("parentElement").appendChild(newDiv);
    // Result: A new div with the text "New dynamically added element" will be added to the parent element.
    </script>

  • removeChild() – Remove a child element from an element.
    Example:
    <div id="removeMe">This will be removed</div>
    <script>
    let elementToRemove = document.getElementById("removeMe");
    document.body.removeChild(elementToRemove);
    // Result: The element with ID "removeMe" will be removed from the page.
    </script>

  • parentNode – Get the parent element of an element.
    Example:
    <div id="parentElement"><div id="childElement">Child</div></div>
    <script>
    let child = document.getElementById("childElement");
    let parent = child.parentNode;
    // Result: The parent element will be logged to the console.
    </script>

  • childNodes – Get all child nodes of an element.
    Example:
    <div id="parentElement"><p>Child 1</p><p>Child 2</p></div>
    <script>
    let children = document.getElementById("parentElement").childNodes;
    // Result: The child nodes (text and paragraphs) of the parent element will be returned.
    </script>

  • nextElementSibling – Get the next sibling element of an element.
    Example:
    <div id="firstElement">First</div><div id="secondElement">Second</div>
    <script>
    let first = document.getElementById("firstElement");
    let nextSibling = first.nextElementSibling;
    // Result: The second element will be returned.
    </script>

  • previousElementSibling – Get the previous sibling element of an element.
    Example:
    <div id="firstElement">First</div><div id="secondElement">Second</div>
    <script>
    let second = document.getElementById("secondElement");
    let prevSibling = second.previousElementSibling;
    // Result: The first element will be returned.
    </script>


πŸ† Working with the JavaScript Elements: End of Lesson Challenge

Test your skills with these challenges:

  1. Create a button that, when clicked, changes the background color of a div.
  2. Add a new paragraph to the page dynamically.
  3. Use querySelectorAll() to change the font size of all paragraphs on the page.

πŸŽ“ Conclusion: Mastering JavaScript Elements

JavaScript gives you powerful tools to interact with and manipulate HTML elements on a webpage. By mastering methods like getElementById(), querySelector(), and classList, you’ll be able to create dynamic and interactive websites. Keep practicing, and soon you’ll be a DOM manipulation pro! πŸš€