attributes
- returns an array of all the attributes of this element. Does not work with Internet Explorer below version 6.
data
- returns or sets the textual data of the node
nodeName
- returns the name of the node (the HTML element name)
nodeType
- returns the type of the node — 1 is an element node, 2 attribute and 3 text.
nodeValue
- returns or sets the value of the node. This value is the text when the node is a textnode, the attribute if it is an attribute or null if it is an element.
getAttribute(attribute)
- returns the value of the attribute
attribute
.
Javascript: var other=document.getElementById('nav').firstChild; if(other.nodeType==3) { other.data='newtext'; } if(other.nodeType==1) { other.firstChild.data='newtext'; }
Now to reach the image in our example, we can use eithergetElementsByTagName
orgetElementById
.
Example:
HTML: Javascript: function findimg() { var image; image=document.getElementById('home'); if (image) { image.style.border='3px dashed #ccc'; } } or: function findimg() { var imgs,i; imgs=document.getElementsByTagName('img'); for(i in imgs) { if(/home.gif/.test(imgs[i].src)) { imgs[i].style.border='3px dashed #ccc'; } } }
Using
getElementById
is a lot easier, as we don't have to loop through all elements and find a unique identifier. In this example, we checked if the src attribute of the image object contains 'home.gif'. A more common way is to check for a special class. Eample:
HTML: Javascript: function findimg() { var imgs,i; imgs=document.getElementsByTagName('img'); for(i in imgs) { if(/roll/.test(imgs[i].className)) { imgs[i].style.border='3px dashed #ccc'; } } }
Now, to add a roll-over effect, all we need to do is to add a function that does the switching of the image source, and adds the event handlers to the image.
function findimg() { var imgs,i; // loop through all images of the document imgs=document.getElementsByTagName('img'); for(i=0;iGood for the moment, but we forgot one thing: Albeit being merely eye candy, a rollover should work without a mouse, too. To achieve this, we need to check if the link around the image gets the focus or not, as the image itself is not reachable via the keyboard when embedded in a link.
To do this, we need to get the element that contains the image, in this case the link. We do this via
parentNode
command. As this also changes the object that gets sent as a parameter to the function roll()
, we need to find the image again. Hence we loop through the childNodes of the link and check which one is an element and an image by checking nodeType
and nodeName
. This is necessary, as some browsers see whitespace in the source as an own node, whereas others don't.function findimg() { var imgs,i; // Loop through all images, check if they contain the class roll imgs=document.getElementsByTagName('img'); for(i=0;i
0 comments:
Post a Comment