Skip to the content.

Javascript with HTML DOM • 3 min read

Home HTML Data Types DOM JavaScript JS Debugging

Hacks

  • Copy your HTML code from the HTML hacks. Write a Javascript snippet to switch the links of the two a tags when a button is pressed. Once they are switched, change the inner HTML of the top p tag to the word “switched!”
%%html

<!--Link to External CSS which styles Button-->
<head>
  <link rel="stylesheet" href="/student/assets/css/basics.css">
</head>

<!--Styling for the DIV-->
<style>
  #paragraph {
    text-align: center;
    font-weight: 500;
  }
</style>
  
  <!--Div containing Paragraph & Button-->
  <div id="paragraph">
      <p id="text">This button needs to be paired with DOM</p>
      <button class="button" onclick="switchText()">Click Me</button>
  </div>

<!--When the Button is Clicked, Modify the Paragraph with the ID of "text"-->
<script id="text">
  function switchText() {
    // Get Paragraph Element (<p id="text">This button needs to be paired with DOM</p>)
    let textDisplay = document.getElementById("text");
    
    //Get Only the Text; aka remove the paragraph tags
    let currentText = textDisplay.innerHTML;

    //If the current text is "Needs to be Paired", then switch the text, else switch it back
    if (currentText === "This button needs to be paired with DOM") {
      textDisplay.innerHTML = "Now it's paired with DOM";
    } else {
      textDisplay.innerHTML = "This button needs to be paired with DOM";
    }
  }
</script>

This button needs to be paired with DOM