Manipulating the Dom!

A simple primer, Prepared by Zoe F , examples by Eric Holland

Setting up our document

  • Let's create for ourselves three text documents: index.html, dom-demoCSS.css, and javascript-file.js
  • Let's set up our html file as normal.

    <!doctype html>
    <html>
    <head>
    </head>
    <body> </body>
    </html
  • Now, let's link to our other two files. Assuming that they're all in the same folder, it should look like this in our header.
    <link rel="stylesheet" href="dom-demoCSS.css">
    <script src="javascript-file.js"></script>
  • Test that our CSS file is communicating withyour html by changing the background color of your body tag in your CSS file.
    body {background-color: lightyellow;}
  • Test that your Javascript file is communicating with your html by putting an alert in it.
    alert("Yep, I'm working");
 

Creating our first manipulation

  • In our Body, let's create a paragraph with the ID myFirstParagraph for us to mess with, and let's put some text content in it.
    <p id = "myFirstParagraph">Hello, I'm just some text minding my own business!</p>
  • Let's style all of the paragraphs we'll use today in our CSS file, and test it:
    p  {
        width:300px;
        border:1px solid black;
        padding:10px;
        margin:0px;
    }
  • Now, let's create a button, and when it's clicked let's call a new javascript function we're gong to define ourselves called change_content().
    <button onclick = "change_content();">See it in Action</button>
    
  • Let's style all of our buttons in our CSS file as well!
    button {
         background-color: lightblue; 
         color: black; 
         font-size: 25px; 
         margin: 10px;
    }          
  • Does that all look good? Great. We don't want to mind our own business, so let's give that function some javascript instructions to perform whenever the link is clicked (which is to say, wenever onclick triggers our change_content() function) that will replace that text with some new text. In our javascript file, let's create a definition for our new function. At the moment it takes no arguments, so we can just call it change_content() with nothing inside the parenthases.
    function change_content() {
    };
    Now we're ready to give it some instructions to replace that line of text for us. Let's use dot notation and add those instructions inside our curly brackets. First let's call on the document:
    document.
    Then let's use the getElementByID method to specifically target our myFirstParagraph <P> tag.
    document.getElementById("myFirstParagraph")
    Great. Now we need to pick what we want to change! We want to change the html content inside that tag's minding its own business. So let's target that.
    document.getElementById("myFirstParagraph").innerHTML
    And finally, let's give it a new content string to replace the old content that was there before!
    document.getElementById("myFirstParagraph").innerHTML = "Wait, the content in this tag has been replaced by a new string!";
  • And test it out. If you've got a bug, try adding an alert or using your console.log(); function to figure out where it's coming from - are you at least triggering your function?
  • You might find it useful to add comments to both your html and javascript files so you don't get things confused! In your html, try adding
    <!--Example 1: A simple paragraph text swap-->
    on top of this first example. In your javascript file, let's do the same by adding
    //Example 1
    at the top of this example.
document

onclick

getElementByID()

innerHTML

A manipulation that takes arguments

  • In our Body, let's add two linebreaks after our first example, and then create a new paragraph. Let's use comments to lable it appropriately.
    <BR><BR>
    <!--Example 2 - swapping back and forth-->
    <p id = "mySecondParagraph">I havn't been clicked yet!</p>
  • This time let's give it two buttons, and, when onclick is triggered, let's have them call a function called change_more_content(). Let's let change_more_content take one argument. The first button should give it the argument "left" and the second button let's use the argument "right". Both are just random strings we're sending. We could actually make them anything.
    <button onclick = "change_more_content('left');">Button One!</button>
    <button onclick = "change_more_content('right');">Button Two!</button>
  • In our Javascript file, let's define the function change_more_content (). The argument that we're sending, we'll store in our new varialbe whichButton
    //example 2
    function change_more_content(whichButton) { };
  • Now let's give it some instructions inside there. We're going to target the inner HTML of our paragraph:
    document.getElementById("mySecondParagraph").innerHTML =
    And let's have it equal some new text that uses the argument string that we're passing in! Let's concatinate the argument with some more text, and make the whole thing replace the current innerHTML there. The string should be:

    "I just <B>clicked</b> the " + whichButton + " button!";
    So the whole instruction together will read:

    document.getElementById("mySecondParagraph").innerHTML = "I just <B>clicked</b> the " + whichButton + " button!";
  • Test it out!
 

Clearing content

  • I want a third button that will get rid of all the content inside this paragraph! Let's create a button that calls a new function called clear_content(), which takes no arguments.

    <button onclick = "clear_content();">Clear Me!</button>
  • And in our Javascript, let's define clear_content()

    //Example 3        
    function clear_content() {
    };
  • Now let's give it some instructions! We want to take this innerHTML, but instead of setting it to a new string, let's set it to an empty string!
    document.getElementById("mySecondParagraph").innerHTML = "";
  • Test it out!

Replacing content

  • Let's try to replace just part of a peice of content, not the whole thing. Let's make a new Paragraph,

    <!--Example 4-->
    <BR><BR>
    <p id = "myThirdParagraph"> My Name is Zoe! Here is a picture of me! <BR>
    <img src = 'https://www.squishable.com/mm5/graphics/00000001/about_icon_zoe_130x130.jpg'>
    </p>
  • And lets give it a button that triggers a function called replace_content.

     <button onclick = "replace_content();">Swap some words!</button>
  • Alright, let's define this function! In our Javascript file, let's create our function:
    //Example 4
    function replace_content() {
    };  
  • I don't like my name. I would like to change it, while leaving everything else in this paragraph the same. First, let's get the existing innerHTML in this paragraph, and set it to a new variable called existingString.:
    var existingString = document.getElementById("myThirdParagraph").innerHTML;
  • Let's use a new Built-in function called replace. It takes two arguments - the thing you want to remove, and the thing you want to replace it with. In this case, I want to replace "Zoe" with a string of html for Mittens the cat, lord of all fluffiness. Let's make a new variable:
    var new_string =
    And set it equal to the results using our replace function on our variable existingString!
    existingString.replace("Zoe", "Mittens the cat, <i>lord of all fluffiness</i>"); 
    So the whole thing together will read:
    var new_string = existingString.replace("Zoe", "Mittens the cat, <i>lord of all fluffiness</i>");
  • We're almost done, now we just need to replace our old innerHTML with the new hotness we've saved in new_string.
    document.getElementById("myThirdParagraph").innerHTML = new_string; 
replace()

Replacing content using arguments

  • Let's give ourselves a new paragraph to experiment on
    <BR><BR>
    <!--Example 5-->
    <p id = "myFourthParagraph">I want a pet.  I think I'll adopt a dog!</p>
    And let's add two buttons to act on it.

    <button >Get a kitten!</button>
    <button>Get a puppy!</button>
  • Let's hook both buttons up to an onclick that triggers a new function we're going to make called replace_content_with_paramater(). This function will take two arguments, the thing to find, and the thing to replace it with. Let's hook "Get a Kitten" up to replace_content_with_paramater('dog', 'cat'); and "get a puppy" up to "replace_content_with_paramater('cat', 'dog')" The final html will look like this:
    <p id = "myFourthParagraph">I want a pet.  I think I'll adopt a dog!</p>
    <button onclick = "replace_content_with_paramater('dog', 'cat');">Get a kitten!</button>
    <button onclick = "replace_content_with_paramater('cat', 'dog');">Get a puppy!</button>
  • In our Javascript, let's define this function! Note that it takes the two arguments, which we're assigning to the variables pet1 and pet2.
    //Example 5
    function replace_content_with_paramater(pet1,pet2) {
              };
  • First, let's start by getting the innerHTML we're going to operate on, and let's pass it into a new variable called existingString. This might sound familiar, it's what we did in the last example!
    var existingString = document.getElementById("myFourthParagraph").innerHTML;
  • Now, let's use the built-in replace() function to replace pet1 with pet2 inside of that string we've now placed in existingString. Note that I've concatinated pet2 with an exclamation mark because i'm excited!
    var new_string = existingString.replace(pet1, pet2 + "!");
  • And finally, let's write that back out to the screen, inside the paragraph we're replacing.
    document.getElementById("myFourthParagraph").innerHTML = new_string;
  • Bonus: Get it to stop adding extra excalamation points after the first one! :)


Modifying the CSS

  • Cats are obviously better than dogs. They deserve to be in red. Let's make it happen with javascript. When someone clicks on the "Get a Kitten" button, we want the text in this paragraph to turn red. If they click on the "Get a puppy" button, we want the text to turn blue.

    Once we are in our replace_content_with_parameter(pet1,pet2) function we know which button they pressed becasue we passed the arguments to our javascript. If pet1 is "dog", we know they chose "get a kitten" becasue we passed the neccesary values to replace "dog" with "cat".

    In our Javascript function, after we set our paragraph to our new text, but still within our function, let's add another instruction. if "pet1" is "cat", we want to change our html one way. If pet1 is "dog" we want to change it another way.

    Let's start by setting up an if/else statement to decide for us.
    if (pet1=='cat') {
    }
    else {}
    };
  • Now, what should we do inside this if/else? instead of changing the paragraph's innerHTML, we want to change its style. And particularly, we want to change it's color property. Using dot notation, let's manipulate this paragrpah's COlor property, if pet1=='cat'. Then test it!
    document.getElementById("myFourthParagraph").style.color = "#0000FF";
  • But its not enough for us to just change it red if we want a cat - we also want it to be blue if we want a dog. in our else, let's set the color property to blue.
    else {document.getElementById("myFourthParagraph").style.color = "#FF0000"}

    The entire if/else statement will look like this:
    if (pet1=='cat') {
    document.getElementById("myFourthParagraph").style.color = "#0000FF";
    }
    else {document.getElementById("myFourthParagraph").style.color = "#FF0000"}
style

Are you stuck? Here are the answers, but don't touch 'em unless you're all done! HTML/Javascript/CSS