Manipulating Attributes


At this point you are probably wondering how to create more complex elements complete with attributes. The DOM Level 1 supports numerous attribute methods for elements, including getAttribute( name ) , setAttribute(attributename, attributevalue) , and removeAttribute(attributeName) . Under DOM Level 2 there is even a very useful Node object method, hasAttributes() , that can be used to determine if an element has any defined attributes. We won t go into too much detail here, given the similarity of these methods to those we have already seen. The following example should illustrate attribute manipulation sufficiently:

 <<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">> <<html xmlns="http://www.w3.org/1999/xhtml">> <<head>> <<title>>Attribute Test<</title>> <<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />> <</head>> <<body>> <<font id="test" size="2" color="red">>Change my attributes!<</font>> <<script type="text/javascript">> <<!--       theElement = document.getElementById('test'); //-->> <</script>> <<form name="testform" id="testform" action="#" method="get">> Color: <<input type="text" id="color" name="color" value="" size="8" />>     <<input type="button" value="Set Color"  onclick="theElement.setAttribute('color',document.testform.color.value);" />> <<input type="button" value="Remove Color"  onclick="theElement.removeAttribute('color');" />> <<br />> Size:  <<select onchange="theElement.setAttribute('size',this.options[this.selectedIndex].text);">>   <<option>>1<</option>>   <<option>>2<</option>>   <<option selected="selected">>3<</option>>   <<option>>4<</option>>   <<option>>5<</option>>   <<option>>6<</option>>   <<option>>7<</option>> <</select>> <</form>> <<script type="text/javascript">> <<!--   document.testform.color.value = theElement.getAttribute('color'); //-->> <</script>> <</body>> <</html>> 
Note  

The << font >> tag is generally frowned upon in the emerging CSS-focused Web, but for this demo it was useful since its attributes show visual changes in a dramatic way.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net