Search code examples
javascripthtmlinnerhtmlgetelementbyid

JavaScript and HTML Assignment .getElementById and .innerHTML


The assignment has me follow step by step instructions to execute code using an HTML button, then getElementById and innerHTML JavaScript. I got the button part to work, but I cannot get the JavaScript to work.

Here's the body of my code:

<body>
    <script type="text/javascript">
        var x= "JavaScript is fun. ";

        document.writeln(x);

        document.writeln(x + x + x + x + x);

        function statement(x)
        {
            return document.writeln(x);
        }   

        document.getElementById("change").innerHTML = x+x+x+x+x;
    </script>

    <button onclick="statement(x)">Click me!</button>
    <p id="change">This will change</p>

</body>

Here are the instructions I was given:

  • So if we wanted to print out that JavaScript is fun below the button, we could instead of having it write to the document itself, we could have it replace some text within a certain element (HTML tag) within the document.

  • So underneath the button, let’s put a paragraph tag and have it read “this will change”

  • We are going to change the innerHTML property of this tag. The innerHTML of a tag is the stuff that is in between the opening and closing tags, which in this case is the text “this will change”

  • First we need to, within JavaScript, identify the tag that we want to change. We can do this by using the getElementById() method. This method simply locates an element with a specified id (similar to intrapage links). So place an id attribute in the opening paragraph tag (i.e. ) and then place the same id in the () (i.e. getElementById(“change”).

  • Once again I said we will change the innerHTML property of this element, so we will attach the innerHTML property to it by saying getElementById(“change”).innerHTML

  • Not all we need to do is say which object this element is associated with. It is within the document, so we can use the document object and specify that by saying document.getElementById(“change”).innerHTML

  • Now that we have identified what we want to change, let’s change it. We do that by setting what we want to change to be equal to the new value, so for me it is: document.getElementById(“change”).innerHTML = x+x+x+x+x;


Solution

  • Try this:

    var x = "JavaScript is fun. ";
    
    function statement(x) {
      document.getElementById("change").innerHTML = x + x + x + x + x;
    }
    <body>
    
      <button onclick="statement(x)">Click me!</button>
      <p id="change">This will change</p>
    
    </body>