Working with Attributes


newLink.setAttribute(   "href", "http://www.samspublishing.com/"); 

So far, this chapter's phrases have covered both regular tags and text nodes. The one major thing still missing is attributes. You can access attributes in the form of nodes, but the most convenient way is to use the setAttribute() method: Just provide the attribute name and its value. In the following code, the contents of the new <li> items are a hyperlink, with an HRef attribute set:

Setting Attributes (attributes.html)

<script language="JavaScript"   type="text/javascript"> var nr = 1; function addItem() {   var list = document.getElementById("list");   var newNode = document.createElement("li");   var newLink = document.createElement("a");   newLink.setAttribute("href",     "http://www.samspublishing.com/");   nr++;   var newTextNode =     document.createTextNode("Item " + nr);   newLink.appendChild(newTextNode);   newNode.appendChild(newLink);   list.appendChild(newNode); } </script> <ul ><li>Item 1</li></ul> <input type="button" onclick="addItem();"   value="Add item" /> 

Figure 5.5 shows that all links added to the list do point to the provided URL.

Figure 5.5. Dynamically generated hyperlinks.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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