ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Beginner JavaScript Tutorial Series: Accessing the HTML DOM (Document Object Model) With JavaScript (Part I)

Updated on May 13, 2014

Recap of the Last Tutorial in the Series

In our last tutorial, A Beginner JavaScript Tutorial Series: Program Logic Statements - if....else, while, for, and switch Statements we introduced the major "decision making" program constructs. We take a break now as a bit of a teaser and demonstrate the use of the HTML DOM. This is really where the action is as far as JavaScript. We will demonstrate how JavaScript, a client-side scripting language can modify the content of a web page. Most of what follows is basic. If you have problems understanding it just put it aside and refer to it as you continue the tutorial series and your JavaScript knowledge grows.

What Can JavaScript Do?

JavaScript can manipulate all of the HTML on a page by accessing the HTML DOM

The HTML DOM (Document Object Model) of the page is created by the browser when the page loads. The DOM can be thought of a a group of objects arranged in a hierarchical fashion.

What actions can JavaScript perform on the DOM?

JavaScript can add, change, and remove all HTML elements and attributes of the web page. Further, it can change all of the CSS styling. JavaScript can all interact with all events associated with the page as well as create new events.

The DOM is a W3C Standard

The DOM is a W3C (World Wide Web Consortium) standard. which is defines how documents can be accessed. The HTML DOM standard is the part which is of interest to those working with web pages. The HTML DOM standard defines an object model and programming interface for HTML:


  • all HTML elements are defined as objects

  • the HTML elements each have specific “class” properties

  • the standard defines methods for the elements

  • the events associated with HTML elements.


The HTML DOM – An Object Oriented Programming (OOP) Implementation

In OOP one uses the term methods for the programming constructs which causes some action to occur which respect to an HTML element or CSS style. Values which can be changed are referred to as properties.

Accessing the Properties of an HTML Element

The most elementary way of getting access to a HTML element is through the element id attribute.

As a refresher, the id of an element can refer to one and only one HTML object. For example:

<p id=”first”> This is a paragraph</p>

The id first must be used uniquely with this document. There cannot be another paragraph with an id of "first" in the web page code.

The method, getElementById would be used as follows to gain access to the HTML paragraph object as follows:

getElementById(“first”)

To obtain the content of the element the innerHTML property is used.

Thus, our access statement for the text of the paragraph becomes:

getElementById(“first”).innerHTML.

The snapshot which follows gives the complete coding for this example.


Illustrating the Use of the getElementById() Method

We reference the paragraph by invoking the getElementById() method with the id specified in the  tag. The we access the property (the value), paragraph text. and perform the write.
We reference the paragraph by invoking the getElementById() method with the id specified in the tag. The we access the property (the value), paragraph text. and perform the write.

HTML document Methods

All methods operate on the “document object. Therefore, all access will be coded as:

document.{some method name}

The actions to be performed on the document are:

Locating the document – some examples being:

  • document.getElementById() (our previous example)

  • document.getElementByTagName()

  • documentgetElementByClassName()

Changing elements (by making an assignment) -

  • element.innerHTML()= )our previous example)

  • element.setAttribute(attribute, value)=

  • element.style.property=

Adding and Deleting elements

  • element.createElement()

  • element.appendChild()

  • element.removeChild()

  • element.replaceChild()

Adding an Event Handler

  • document.getElementById(id).eventname=function(){code}

The next sections investigate these methods further and give examples.

Using the getElementByTagName

As previously noted there are several ways to locate HTML elements.

Our previous example demonstrated the use of getElementById() method.

Another way of locating HTML elements is with the getElementsByTagName() method. The getElementsByTagName() returns a collection of an elements's child elements with the specified tagname, Note that even though there is only one paragraph in the referenced element we need to access the paragraph in array notation. We have not covered arrays as yet in this tutorial series, but if you have encountered arrays in other programming languages, the concept should be faimiliar. An arrary is a set of items which is identified by one name. To reference individual objects, one specifies an index. The index is a number starting at one. So, if the array is named "y" as in our example, the first element is referred to as y[0], the second as y[1}, etc.

The following snapshot the use of document.getElementByTagName().

A getElementByTagName() Example

In this example we are first looking for a HTML element called "div1"  and within that item we want to locate  tags. The getElementByTagName was used. As this method may return 0 or more  tags an array is utlilized.
In this example we are first looking for a HTML element called "div1" and within that item we want to locate tags. The getElementByTagName was used. As this method may return 0 or more tags an array is utlilized.

Finding HTML Elements by Object Collections

The previous example illustrated the use of the getElementByTagName(). This method returns all elements which match the method argument. We noted that the returned value(s) ( which can be null, one, or many) are processed as items in an array. The formal name for this array is a HTML Collection.


The following HTML object collections are accessible:

  • document.anchors

  • document.forms

  • document.images

  • document.links



HTML DOM Changing Text with JavaScript

The ability to change text with the use of JavaScript makes the pages dynamic. As we proceed through this and the next tutorial we can not only change the HTML content but we can modify the CSS styling as well.

In our next simple example, the text contained within the HTML paragraph element was set to "Greeting earthlings!" with the use of the JavaScript statement:

document.getElementById("p1").innerHTML="How's things on Mars?";

the text was changed before it was displayed. The key here is the assignment operator. We first obtained the location of the element "p1" with the use of the getElementById() method and then accessed the text of the paragraph by referencing the innerHTML property and assigned it the new value, the string, "How's things on Mars?".

A Simple Text Substitution Using JavaScript

A simple text substitution which is performed by accessing the target paragraph and the assigning the new value to the innerHTML property.
A simple text substitution which is performed by accessing the target paragraph and the assigning the new value to the innerHTML property.

Writing Dynamic Information to the Page

The following snapshot illustrates the use of the Date() method in writing current information to the screen. Further examples in the next part of this tutorial will demonstrate the implementation of a real time clock.

Using a Call to a Date() Function Within a Script

This illustrates the simplicity of using JavaScript., if perhaps you wanted the current date and time at which the page had been accessed to be displayed.
This illustrates the simplicity of using JavaScript., if perhaps you wanted the current date and time at which the page had been accessed to be displayed.

Wrap Up and What's Next

In this tutorial we introduced the HTML DOM (Document Object Model) and demonstrated several methods for accessing the HTML content and modifying it. These examples are just "mock ups" illustrating the functionality. In the next tutorial, Part II, we will show how currently displayed text can be modified through events.

There are many ways in programming to solve the same problems. Our illustrations for the next tutorials will try to show different ways of accomplishing the same task.

Part II will also look at modifying the CSS styling of a page with the help of JavaScript.

Please Apprise Us of Your Understanding of This Tutorial

3 out of 5 stars from 1 rating of Was this tutorial and its examples clear?

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)