How to Use JavaScript's GetElementById to Access a Specific Element

You can use JavaScript to access an element within an HTML page. You might do this to make changes to the element or to the CSS styling. Try it out in an exercise.

  1. Open your text editor with a new or blank document.

    image0.jpg
  2. In the text editor, place the following HTML and JavaScript:

    <!doctype html>
    <html>
    <head>
    <title>Chapter 2</title>
    </head>
    <body>
    <div id="myDiv">Hello</div>
    <div class="divClass">Second Line</div>
    <div class="divClass">
        <p class="pClass">This is in a paragraph.</p>
    </div>
    <div class="divClass">Last Line</div>
     
    <script type="text/javascript">
        var theDiv = document.getElementById("myDiv");
        alert("The content is " + theDiv.innerHTML);
    </script>
     
    </body>
    </html>
  3. Save the file as getbyid.html in your document root.

    image1.jpg
  4. Open your web browser and view the page at http://localhost/getbyid.html.

    You should see an alert like the one shown here.

    image2.jpg
  5. Click OK to dismiss the alert and close your browser.

  6. Back within getbyid.html in your editor, remove the JavaScript line that begins with alert. Replace that line with these two:

    theDiv.style.border = "3px solid black";
    theDiv.innerHTML = "This is now changed text.";

    The entire script block should now look like this:

    <script type="text/javascript">
        var theDiv = document.getElementById("myDiv");
        theDiv.style.border = "3px solid black";
        theDiv.innerHTML = "This is now changed text.";
    </script>

    When viewed in a browser, the page now looks like that shown here. Notice specifically that the text of the top line has been changed and now has a border.

    image3.jpg
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.