To create the DOM for a document, each element in the HTML is represented by
what’s known as a node.

The most direct path to an element is via its id attribute.
HTML:
<p id="uniqueElement">
...
</p>
JavaScript:
var target = document.getElementById("uniqueElement");
JavaScript:
var indigo = document.getElementById("uniqueElement");
indigo.style.backgroundColor = "#000066";
Example 1 - Example 2 (unobtrusive)
JavaScript:
var listItems = document.getElementsByTagName("li");
Use the getAttribute method to find the value of an attribute.
HTML:
<a id="picLink" href="images/image-1.jpg" rel="lightbox" title="my caption"> image #1 </a>
JavaScript:
var theTitle = document.getElementById("picLink").getAttribute("title");
Use setAttribute to change the value of an attribute node.
JavaScript:
var shopping = document.getElementById("purchases");
shopping.setAttribute("title","a list of goods");
This Image Gallery script uses getAttribute and setAttribute
function showPic(whichpic) {
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src",source);
}
<a href="images/fireworks.jpg" onclick="showPic(this); return false;">Fireworks</a>
<a href="images/fireworks.jpg" onclick="showPic(this); return false;">Fireworks</a>
The action starts when the user clicks the link
this is a special JavaScript keyword that behaves like a variable, except that you can’t assign it a value—its value is the object upon which the currently-executing function was invoked as a method.
We name the function and name the argument that gets passed to the function:
function showPic(whichpic)
var source = whichpic.getAttribute("href");
whichpic represents the a attribute that gets passed to the function.
<a href="images/fireworks.jpg" onclick="showPic(this); return false;">Fireworks</a>
var placeholder = document.getElementById("placeholder");
This assigns the image placeholder element to a variable.
<img id="placeholder" src="images/placeholder.gif" alt="my image gallery" />
placeholder.setAttribute("src",source);
This updates the src attribute of the image placeholder element with the value of the href from the link we clicked.
The 3 lines of code in the showPic function could have also been written as:
document.getElementById("placeholder").setAttribute("src",whichpic.getAttribute("href"));
We name the function and name the argument that gets passed to the function:
function showPic(whichpic)
We name the function and name the argument that gets passed to the function:
function showPic(whichpic)
We name the function and name the argument that gets passed to the function:
function showPic(whichpic)