Home

Using Javascript with HTML DOM

Home HTML JavaScript DOM Data Types Correcting errors

Following along

Remember to “git pull” on teacher repository to update to lates.

Referencing HTML elements using javascript

%%html
<!-- the ID must be specified within the element -->
<h1 id="domTitleID">My Title</h1>

<!-- javascript goes here -->
<script>
var titleElement = document.getElementById("domTitleID")
<!-- outputs h1 tag -->
console.log("Example #1, show element in DOM")
console.log(titleElement)
</script>

Getting the data within the HTML element

%%html
<!-- the ID must be specified within the element -->
<h1 id="domTitleIDget">My Title</h1>

<!-- javascript goes here -->
<script>
var titleElement = document.getElementById("domTitleIDget")
<!-- outputs h1 innerHTML from h1 tag -->
console.log("Example #2, show innerHTML")
console.log(titleElement.innerHTML)
</script>

Setting the data within the HTML Element

%%html
<!-- the ID must be specified on the element -->
<h1 id="domTitleIDset">My Title</h1>

<!-- javascript goes here -->
<script>
var titleElement = document.getElementById("domTitleIDset")
titleElement.innerHTML = "Set and Update My Title"
<!-- outputs h1 innerHTML after h1 tag has been updated -->
console.log("Example #3, update innerHTML")
console.log(titleElement.innerHTML)
</script>

Creating elements

%%html
<!-- the ID must be specified on the element -->
<div id="divContainerID">
    <h1 id="h1ElementID">My Title</h1>
</div>

<!-- javascript goes here -->
<script>
   // creates a new element
   var pElement = document.createElement("p")
   pElement.innerHTML = "Starting a paragraph of text."
   
   // outputs p tag after it has been created
   console.log("Example #4, create a p tag within JS")
   console.log(pElement)
</script>

Issue! How to Create element that appears in HTML?

Solution

%%html
<!-- the ID must be specified on the element -->
<div id="divContainerIDset">
    <h1 id="h1ElementIDset">My Title</h1>
</div>

<!-- javascript goes here -->
<script>
   // creates a new element
   var pElement = document.createElement("p")
   pElement.innerHTML = "Starting a paragraph of text."
   
   // outputs p tag after it has been created
   console.log("Example #5, add p tag to HTML")
   console.log(pElement)
   
   // place the p element inside the HTML page
   var div = document.getElementById("divContainerIDset")
   div.appendChild(pElement)
</script>

Functions in JavaScript, using with DOM

Creeating functions

%%html
<!-- the ID must be specified on the element -->
<div id="divContainerIDfunction">
    <h1 id="h1ElementIDfunction">My Title</h1>
</div>

<!-- javascript goew here -->
<script>
    // define a function => takes parameter text, returns a new p tab
    function createPTag(text) {
        // creates a new element
        var pElement = document.createElement("p")

        // using the parameter like a variable
        pElement.innerHTML = text
        
        // outputs p tag after it has been created
        console.log("Example #6, add p tag using a function")
        console.log(pElement)

        return pElement;
    }

    // using a function to create p tag
    var pTag = createPTag("Starting a paragraph with cooler text than before.")

    // place the p element in the webpage
    var div = document.getElementById("divContainerIDfunction")
    div.appendChild(pTag)
</script>

OnClick Event

%%html
<!-- the ID must be specified on the elements -->
<button id="buttonID">Click here!</button>

<div id="divContainerIDbutton">
    <h1 id="h1ElementIDbutton">My Title</h1>
</div>

<!-- our javascript goe here -->
<script>
    // define a function => takes parameter text, returns a new p tab
    function createPTag(text) {
        // creates a new element
        var pElement = document.createElement("p")

        // using the parameter like a variable
        pElement.innerHTML = text
        
        // outputs p tag after it has been created
        console.log("Example #7.1, add p tag using a function")
        console.log(pElement)

        return pElement;
    }

    // create a function that sets specific text and adds to div
    function addPTagOnButton() {
        // using our new function
        var pTag = createPTag("Starting a paragraph with text created on button press.")

        // place the p element in the webpage
        var div = document.getElementById("divContainerIDbutton")

        // add p tag to the div
        div.appendChild(pTag)
        
        // outputs p tag after it has been created
        console.log("Example #7.2, update container adding a 'p' tag")
        console.log(div)
    }

    // add the P tag when our button is clicked
    var myButton = document.getElementById("buttonID")
    myButton.onclick = addPTagOnButton
    
</script>

Hacks

Hack solution number 1


%%html

<style>
    .Text p{
        align-items: center;
    }
    button {
        padding: 10px 20px;
        background-color: #007bff;
        color: #fff;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-left: 40%;
      }
      button:hover {
        background-color: #0056b3;
      }
</style>
<div class="Text">
    <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae, quod reiciendis neque odit ipsam similique, adipisci rem iusto dignissimos est facere? Nemo repellendus perferendis corporis neque eius eveniet eligendi sequi!</p>
    <br>
    <button id="testbutton">Test Button</button>
</div>

<br>
<br>

<div class="Links">
    <a target="_blank" href="https://poway.instructure.com/">Canvas</a>
    <br>
    <br>
    <a target="_blank" href="https://github.com/">Github</a>
    <br>
    <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Provident maiores, dolorum officiis qui iure, delectus eum enim minus facere eius quisquam! Veniam nostrum tempora alias natus praesentium in accusantium laborum!</p>
</div>

<script>
    var originalText = document.querySelector('.Text p').innerHTML;
    var originalLinks = {
        firstLink: document.querySelectorAll('.Links a')[0].getAttribute('href'),
        firstLinkText: document.querySelectorAll('.Links a')[0].innerHTML,
        secondLink: document.querySelectorAll('.Links a')[1].getAttribute('href'),
        secondLinkText: document.querySelectorAll('.Links a')[1].innerHTML
    };

    var isReverted = false;

    document.getElementById('testbutton').addEventListener('click', function() {
        if (isReverted) {
            // Revert links and text to original values
            document.querySelectorAll('.Links a')[0].setAttribute('href', originalLinks.firstLink);
            document.querySelectorAll('.Links a')[0].innerHTML = originalLinks.firstLinkText;
            document.querySelectorAll('.Links a')[1].setAttribute('href', originalLinks.secondLink);
            document.querySelectorAll('.Links a')[1].innerHTML = originalLinks.secondLinkText;
            document.querySelector('.Text p').innerHTML = originalText;
        } else {
            // Change links and text
            var tempLink = document.querySelectorAll('.Links a')[0].getAttribute('href');
            var tempText = document.querySelectorAll('.Links a')[0].innerHTML;
            document.querySelectorAll('.Links a')[0].setAttribute('href', document.querySelectorAll('.Links a')[1].getAttribute('href'));
            document.querySelectorAll('.Links a')[0].innerHTML = document.querySelectorAll('.Links a')[1].innerHTML;
            document.querySelectorAll('.Links a')[1].setAttribute('href', tempLink);
            document.querySelectorAll('.Links a')[1].innerHTML = tempText;
            document.querySelector('.Text p').innerHTML = "Switched!";
        }

        isReverted = !isReverted; // Toggle the state for the next click
    });
</script>



Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae, quod reiciendis neque odit ipsam similique, adipisci rem iusto dignissimos est facere? Nemo repellendus perferendis corporis neque eius eveniet eligendi sequi!




Hack solution number 2


%%html

<head>
<style>
    .Text p{
        align-items: center;
    }
    button {
        padding: 10px 20px;
        background-color: #007bff;
        color: #fff;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-left: 40%;
      }
      button:hover {
        background-color: #0056b3;
      }
</style>
</head>

<body>
    <h1 id="domTitleID">Adding paragraphs</h1>
    <div id="divContainerID">
        <h2>Dynamic Content:</h2>
    </div>
    <button id="addParagraphButton">Add Paragraph</button>
</body>

<script>
    // Function to create a new paragraph element with the given text
    function createParagraph(text) {
    var pElement = document.createElement("p");
    pElement.innerHTML = text;
    return pElement;
    }

    // Function to add a paragraph to the container
    function addParagraphToContainer() {
    var container = document.getElementById("divContainerID");
    var text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae, quod reiciendis neque odit ipsam similique, adipisci rem iusto dignissimos est facere? Nemo repellendus perferendis corporis neque eius eveniet eligendi sequi!";
    var paragraph = createParagraph(text);
    container.appendChild(paragraph);
    }

    // Attach the click event handler to the button
    var addButton = document.getElementById("addParagraphButton");
    addButton.onclick = addParagraphToContainer;
</script>

Adding paragraphs

Dynamic Content:

© 2024    •  Powered by Soopr   •  Theme  Moonwalk