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

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

By Steve Suehring, Janet Valade

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.


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

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


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

    You should see an alert like the one shown here.


  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: = "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"); = "3px solid black";
        theDiv.innerHTML = "This is now changed text.";

    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.