1. Computing

JavaScript By Example

Document Object Model: 10. Get Attributes

By

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.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D10</title>
</head>
<body>
<form action="#">
<div>
<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>
</div>
</form>
<p id="txt"></p>
<script type="text/javascript" src="exampleD10.js"></script>
</body>
</html>

JavaScript


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. Computing
  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.