Joshua Mendoza
JfuseCodes

JfuseCodes

Can Javascript change HTML content?

Joshua Mendoza's photo
Joshua Mendoza
·Jul 25, 2022·

4 min read

Can Javascript change HTML content?

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • DOM
  • Events
  • EXERCISE
  • Whats Next?

Hyper Text Markup Language(HTML), Cascading Style Sheets(CSS) and Javascript all go hand in hand. You can make very simple web pages with just HTML. You can also add some styling with CSS, but it’s by including Javascript that you can make your page come alive through user interactivity.

In this post, I will:

  • Go over the main points of the Document Object Model(DOM)
  • Provide a tutorial that demonstrates HTML interactivity by using some elements of the DOM
  • Practice to someone starting out who might be having trouble with the DOM

DOM

  • What is the DOM?

    • Representation of the document which is a data structure that can be read or modified which allows for manipulation of the content within the HTML file. In order to understand the Document Object Model(DOM), you should understand the structure of a web document, which in this case is the HTML document. The HTML document has tags such as <body> </body, <head></head>, <h1></h1>, etc. The DOM gives programming languages access in order to change or manipulate the content on the document.
  • Javascript can access the DOM by way of objects and nodes using methods

    • Some of those common methods, and ones that I use daily are:
      • querySelectorAll
      • querySelector
      • createElement
      • childNode
      • append
      • innerHTML & textContent
  • Targeting a node you want to work with

    • Using javascript you can target with selectors based on how they are identified within the document.
      • A CSS selector is targeted with document.querySelector(’.class-name’)
      • An ID selector is targeted with document.querySelector(’#idName’)
      • An element selector is targeted with document.querySelector(elementType)
      • Can also select all types that are the same like so:
        • document.querySelectorAll(’.class-name’)
          document.querySelectorAll(’#id-name’)
          
  • Dom Manipulation Examples

    1. Select HTML element
    2. Create an element
    3. Print myHeading to the screen
    4. Append an elements to the HTML tag
const htmlElement = document.querySelector('html'),
           myHeading = document.createElement('h1');

myHeading.textContent = 'My Heading'

htmlElement.append(myHeading);

Events

  • What are events?

    • actions that occur in the web browser like
      • click
      • double click
      • mouse up
  • Listeners

    • A function that is placed on an event which listens to the event that occured. Once that event is triggered the function is ran. Its usually placed on a button to listen for a click, but can also be placed on many other events as well.
  • Ways to use events in your code?

    There are 3 major ways to use events in your code

    1. HTML event handler attributes


<body>
   <!--execute within html element-->
    <input type='button' onclick = 'alert('clicked')'>

   <!--execute within html element but from external javascript file-->
    <input type='button' onclick = 'functionName()'>
</body>

2. Variable onclick property within javascript file

 <body>

  <button id='dombtn1' type='button' name='button'>QuerySelector</button>

  <script>
    const domButton = document.querySelector('#dombtn1');
    domButton.onclick = ( ) => alert("The button was clicked");
  </script>

</body>

3. EventListener Method

  • Provides two main methods:
    • addEventListener()
    • removeEventListener()
  • Benefits:

    • HTML event handler attributes
      • not as popular because it tends to overpopulate the HTML file
    • Element onclick property in javascript
      • This way of using the event allows you to seperate the event and the listener.
  • Examples:

    Add Event Listener
 <body>

  <button id='addEvent' type='button' name='button'>Add Event</button>

  <script>
    const addEventButton = document.querySelector('#addEvent');

/* 
Add Event Listener accepts 3 arguments:
    1. Event Name
    2. Event Handler Function
    3. Boolean value:
        - calls event handler during capture phase if true
        - calls event handler during bubble phase if false    
*/
   addEventButton.addEventListener('click', action = event => alert(event.type));

   const action = event => alert(event.type);


/* 
removeEventListener()
  removes an event listener that was added via addEventListener method
*/
addEventButton.removeEventListener('click', action);
  </script>

</body>

EXERCISE

  • Here are some challenges to build that muscle memory:

    • Start with an index HTML file
    • USING ONLY JAVASCRIPT and the div above, add the following to the HTML page

      • a level 1 heading element tag(<h1>) that says “hello world”
      • a paragraph tag that says “i am a paragraph tag”
      • a div with the following:
        • h1 that says “this was created using DOM manipulation”
        • h3 that says ‘this is all within the same div’
        • p this is the last element within the div
    • Create a button that removes all the above elements from the document

Whats Next?

And there you have it! A mini tutorial on how javascript can change a HTML’s content. Of course theres so much more tools and methods to achieve this task that one can add, but these are the basics that every front end developer should know. We went over the DOM and Events, and I even provided some challenges to help you put that knowledge to use. Now that you know this, it should be easier to create some interactive web apps in the future. Want to learn more about javascript interactivity? Then check out my next article where I create a random color generator using the DOM and Events.

Did you find this article valuable?

Support Joshua Mendoza by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this