1. Technology

JavaScript By Example

Document Object Model: 10. Get Attributes


Now that we have looked at lots of different ways of retrieving specific elements from our web page into nodes and nodelists in our JavaScript we next need to look at how we can access the information associated with those nodes. Over the next few examples we'll look at how to use the properties and methods associated with the nodes that we have accessed to retrieve information about the nodes. We'll cover updating nodes and creating new nodes later.

While there is a getAttributes() method available to access the attributes of a node that method does not always work as expected in some old but still popular browsers. We don't need to use that method to retrieve the values from specific attributes as all of the attributes are also directly attached to the node as properties. In almost all cases the name of the property is the same as the name of the attribute and so as demonstrated in the below example we can access the value of the name attribute of a tag by referencing the name property of the corresponding node. The exceptions are where the attribute name matches a JavaScript reserved word and so the class attribute becomes the className property and the for attribute becomes the HTMLfor property.


<title>Example D10</title>
<form action="#">
<input type="radio" id="r1" name="size" value="s" />
<label for="r1">Small</label>
<input type="radio" id="r2" name="size" value="m" />
<label for="r2">Medium</label>
<input type="radio" id="r3" name="size" value="l" />
<label for="r3">Large</label>
<p id="txt"></p>
<script type="text/javascript" src="exampleD10.js"></script>


var rad, tx;
rad = document.getElementById('r1');
tx = 'The value of the name attribute of the first radio button is "' +
  rad.name + '"';
document.getElementById('txt').innerHTML = tx;

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Get Attributes

©2014 About.com. All rights reserved.