javaScript  HTMLdom  access

accessing html nodes (elements)

the javaScript language provides rich set of methods for access an html element such as:

  • the getElementById() method
  • the getElementsByTagName() method
  • the getElementsByClassName() method

JavaScript - getElementById() method

the getElementById() method returns a reference to the first object with the specified value of the id attribute .


          var  obj = document.getElementById("id_value")
  • id_value : a string that specifies the value of the id attribute.

note : if more than one element is found, this method returns the first object in the collection.

note : if no element is found, the getElementById() method return null.

this example finds the element with id='p'

      <p id="p" > this is the first paragraph </p>
      <p id="pp"> this is the second paragraph</p>
                 var  obj = document.getElementById('p');
                      alert("p content is______"+obj.innerhtml);

JavaScript - getElementsByClassName() method

if you want to find all html elements with the same class name. use this method


          var  obj = document.getElementsByClassName("value")
  • value : a string that specifies the value of a class attribute.

this example below returns a list of all elements with class='p'.

      <p class="p" > this is getelement by class  </p>
      <p class="p"> this is the javascript access element by class name</p>
                 var  obj = document.getElementsByClassName('p');
                alert("first p content is________"+obj[0].innerhtml);
                alert("second p content_______"+obj[1].innerhtml);

note : the getElementsByClassName() does not work in internet explorer 5,6,7,8.

JavaScript - getElementsByTagName() method

the getElementsByTagName() method returns a list of elements with the given tag name.


          var  obj = document.getElementsByTagName(tag)
  • tag : is a string representing the name of the elements. string  "*"  represents all elements.

this method return a new nodeList object containing all the matched elements.

this example finds all <p> elements and display its content:

  <script>  function  showContent(){
                 var  obj = document.getElementsByTagName('p');
                 var  length = obj.length;  
                 for(var  i=0; i<length; i++){
                                alert("paragraph content ______"+obj[i].innerhtml);
                 document.write("the total <p> elements =="+length);                           
      <p> this is the javascript get element by id </p>
      <p> this is the javascript get element by class name</p>
      <p> this is the javascript get element by tag name</p>
<button onclick='showContent()'>click here to display all paragraph content</button>