DEV Community

avery
avery

Posted on

15. The Document Object Model (DOM)

BootCamp by Dr.Angela

1. Adding JavaScript to Websites

  • <script src="index.js" charset="utf-8"></script>
  • Place the <script> tag at the end of the <body>
  • Ensures JavaScript runs after the HTML elements are loaded
  • Can only manipulate elements that already exist in the DOM

2. Introduction to the DOM

3. Selecting HTML Elements

  • querySelector() : Returns the first matching element, Supports #id, .class, and tag selectors
  • querySelectorAll() : Returns all matching elements (NodeList)
  • getElementsByTagName() : Returns elements by tag name (HTMLCollection)
  • getElementsByClassName() : Returns elements by class name
  • getElementById() : Returns a single element

4. Manipulating Styles

5. Separation of Concerns (Structure vs Style vs Behaviour)

  • Add class : ex) document.querySelector("name").classList.add("className");
  • Remove class : ex) document.querySelector("name").classList.remove("className");
  • Toggle class : ex) document.querySelector("name").classList.toggle("className");

6. Text Manipulation

  • innerHTML(can include HTML) vs textContent(text only)
    • document.querySelector("h1").innerHTML = "<em>Hello</em>";
    • document.querySelector("h1").textContent = "Hello";

7. Manipulating Attributes

  • attributes : shows all attributes
  • getAttribute() : gets attribute value
  • setAttribute() : sets or updates attribute value
    • ex) document.querySelector("a").setAttribute("href", "https://www.bing.com");

Top comments (0)