09.02.2015 Views

DOM Traversal Methods - MarkMail

DOM Traversal Methods - MarkMail

DOM Traversal Methods - MarkMail

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Selector Expressions<br />

Examples<br />

1. $('#myid'): selects the unique element with id='myid', regardless of its<br />

tag name<br />

2. $('p#myid'): selects a single paragraph with an id of 'myid'; in other<br />

words, the unique element <br />

Description<br />

Each id value must be used only once within a document. If more than one element<br />

has been assigned the same id, queries that use that id will only select the first<br />

matched element in the <strong>DOM</strong>.<br />

It might not be immediately clear why someone might want to specify a tag name<br />

associated with a particular id, since that id needs to be unique anyway. However,<br />

some situations in which parts of the <strong>DOM</strong> are user-generated may require a more<br />

specific expression to avoid false positives. Furthermore, when the same script is run<br />

on more than one page, it might be necessary to identify the id's element, since the<br />

pages could be associating the same id with different elements. For example, Page A<br />

might have while Page B has .<br />

For a plain id selector such as example 2 above, jQuery uses the JavaScript function<br />

getElementById(). If the script's execution speed is paramount, the plain id selector<br />

should be used.<br />

Class: .myclass<br />

All elements that have a class of myclass.<br />

Examples<br />

1. $('.myclass'): selects all elements that have a class of myclass<br />

2. $('p.myclass'): selects all paragraphs that have a class of myclass<br />

3. $('.myclass.otherclass'): selects all elements that have a class of<br />

myclass and otherclass<br />

Description<br />

In terms of speed, example 2 is generally preferable to example 1 (if we can limit<br />

the query to a given tag name) because it first uses the native JavaScript function<br />

getElementsByTagName() to filter its search, and then looks for the class within<br />

the matched subset of <strong>DOM</strong> elements. Conversely, there is currently no native<br />

getElementsByClassName() for jQuery to use, so using a bare class name forces<br />

jQuery to match it against every element in the <strong>DOM</strong>. The difference in speed varies,<br />

however, with the complexity of the page and the number of <strong>DOM</strong> elements.<br />

[ 18 ]

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

Saved successfully!

Ooh no, something went wrong!