Madeline Zenz Logo
MADELINE ZENZ

DOM Methods

getElementById


The method getElementById is used to access an element. There is one String parameter which is the id name. The method returns the element with an id attribute with the same value as specified. This method is called by using "document.getElementById" and passing in the id. Below is an example of the method in use where an element with the id of "btnSave" is being accessed. The element, which in this case is a button, is set equal to a variable called "btn".

            
                var btn = document.getElementById("btnSave");
            
        


getElementsByTagName


This method is used to access all elements with a specified tag name. The parameter is a String that's the same as the tag name. This method returns all elements with the specified tag as a NodeList. You can access individual nodes from the list with index numbers and you can also declare the length of the NodeList if you only want to access a certain number of nodes. This example gets all elements with the tag "Header". The for loop then goes through each element with that tag and gives them a blue background.

            
                var x = document.getElementById("myDIV");
                var y = x.getElementsByTagName("Header");
                var i;
                for (i = 0; i < y.length; i++) {
                  y[i].style.backgroundColor = "blue";
                }
            
        


getAttribute


The getAttribute method gives the string value of attribute from an element. There is one string parameter which is the attribute name. This method returns a string representing the value of the specified attribute. The example below shows code that accesses a book element with getElementById and then creates a variable called title. The variable stores the book element's title attribute that is accessed by the "getAttribute" method. The comment shows what the getAttribute method returns

            
                    var book = document.getElementById('book');
                    var title = book.getAttribute('title');
                    // => The Hunger Games
            
        


setAttribute


The setAttribute method is used to replace the value of attribute with a specified value. This method has two string parameters, the attribute name and the attribute value that you would like it to be set to. Then the value of the attribute is set to that second parameter. The method returns undefined since it is only for changing a value. An example below shows an element named dog whose value of the attribute "name" being changed with the setAttribute method.

            
                    dog.setAttribute("name", "Snoopy");