Introduction to JavaScript and DOM

Welcome aboard! In today's lesson, we are exploring the dynamic duo of JavaScript and the Document Object Model (DOM). Working in tandem with the DOM, we can manipulate and update our web pages in real-time based on user interactions.

Do you remember how some websites greet, "Good morning!" during the day and "Good night!" after sundown? This dynamic behavior is exactly what we aim to achieve using JavaScript and DOM.

Linking JavaScript to HTML

To introduce JavaScript into HTML, we need the <script> tag. Although JavaScript can be written directly inside HTML, it's often tidier to store it in separate files:

<!DOCTYPE html>
<html>
  <body>
    <h1>Welcome to My Web Page</h1>
    <p id="demo">This is a paragraph.</p>
    <!-- Linking an external JavaScript file -->
    <script src="myscript.js"></script> 
  </body>
</html>

Inline <script> tags also serve as an option:

<!DOCTYPE html>
<html>
  <body>
    <h1>Welcome to My Web Page</h1>
    <p id="demo">This is a paragraph.</p>
    <!-- Inline JavaScript -->
    <script> 
      // Changing the paragraph text
      document.getElementById("demo").innerHTML = "Hello, there!";
    </script> 
  </body>
</html>

The innerHTML property is a powerful tool that allows us to get the content of elements or directly insert content into elements in our HTML. In the code above, we used innerHTML to change the text content of a paragraph.

Understanding DOM Manipulation

Atomic yet immense, DOM manipulation is achievable via JavaScript. This tool offers us the ability to grasp elements and perform operations on them much like a craftsman working on his creation. Here are some handy methods for DOM manipulation:

  • document.getElementById(id): This function fetches an element using its unique ID, much like how you would find a book in a library.
  • document.getElementsByTagName(name): It selects all elements that share a specified tag name, such as all paragraphs (<p>).
  • document.getElementsByClassName(name): This function retrieves all elements having the provided class name.
  • document.querySelector(selector): Just as you pick out your favorite fruit from a basket, it selects the first element that matches the supplied CSS selector.

Selectors that return multiple elements (getElementsByTagName and getElementsByClassName) return a live HTMLCollection — a special list of elements that can be accessed like a JavaScript array using bracket notation. However, it's important to know it's not actually an array, which means you can't use common array methods like map, filter, or forEach directly on it. To work with a specific element, use its index position.

Below, we have an illustration of how we can select an HTML element and modify its content and style:

<!DOCTYPE html>
<html>
  <body>
    <h1 id="title">Hello World!</h1>
    <button onclick="changeTitle()">Transform title</button>
    <script>
      function changeTitle() {
        // Selects the 'title' element
        let titleElement = document.getElementById('title');
        // Changes the element's content and color
        titleElement.innerHTML = 'Hello JavaScript!';
        titleElement.style.color = 'red';
      }
    </script>
  </body>
</html>

The <button> tag in HTML is used to create a clickable button on your webpage. Contained within the opening and closing <button> tags, you can place text or images. This content is what users see and click on. The onclick attribute is an event attribute that instructs the browser to execute a specific JavaScript function when the button is clicked. The function to be executed is specified right within the onclick attribute.

In this case, once the button is clicked it triggers the changeTitle() method. Within this method, we're setting the style.color property of titleElement. titleElement.style.color = 'red'; alters the CSS color of the text within this element to red.

Using getElements or querySelector to access an element is just the starting point. Once you have the reference to an element, there are many things you can do to manipulate it.

  • Modifying content: As you've seen with innerHTML, after selecting an element, you can directly manipulate its content.

  • Changing style: You can change any CSS property of an element using element.style.property. This covers a range of alterations from colors, dimensions, positioning, to transitions, transformations and visibility. Note: In JavaScript, CSS property names that contain a hyphen (like background-color) are converted to camelCase (becomes backgroundColor). This is due to the fact that hyphens are not allowed in JavaScript variable names.

<script>
  let titleElement = document.getElementById('title');
  titleElement.style.backgroundColor = 'yellow';  //changes the background color of the title element to yellow 
</script>
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal