02.06.2013 Views

DOM Traversal Methods

DOM Traversal Methods

DOM Traversal Methods

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>DOM</strong> Manipulation <strong>Methods</strong><br />

Description<br />

We can get any attribute of an element rather easily without jQuery, by using the<br />

native JavaScript function getAttribute. Additionally, most of these attributes are<br />

available through JavaScript as <strong>DOM</strong> node properties. Some of the more common<br />

properties are:<br />

•<br />

•<br />

•<br />

•<br />

•<br />

•<br />

•<br />

className<br />

tagName<br />

id<br />

href<br />

title<br />

rel<br />

src<br />

Let's consider the following link:<br />

old jQuery links<br />

Using jQuery's .attr method to get an element's attribute has two main advantages:<br />

1. Convenience: it can be chained to a jQuery object.<br />

2. Cross-browser consistency: The .attr method always gets the actual<br />

attribute text, regardless of which browser is being used. On the other hand,<br />

when using getAttribute() with attributes such as href, src, and cite,<br />

some browsers (correctly) get the attribute text, while others get the absolute<br />

URL, regardless of whether the attribute has an absolute URL or a<br />

relative one.<br />

In order to use getAttribute() or any of an element's properties as a substitute for<br />

.attr(), we need to make sure that we are working with a <strong>DOM</strong> node rather than a<br />

jQuery object. To convert the first element represented in a jQuery object to a <strong>DOM</strong><br />

node, we can use either [0] or .get(0).<br />

All of the following use getAttribute('title') to get its title attribute:<br />

1. document.getElementById('myid').getAttribute('title')<br />

2. $('#myid').get(0).getAttribute('title')<br />

3. $('#myid')[0].getAttribute('title')<br />

With any of these options, we could replace .getAttribute('title') with .title.<br />

[ 62 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!