Tuesday, August 24, 2010

Selecting selectors

Selectors are fairly straightforward in jQuery. Here are what some of the basic selectors look like:

$('p')
$('div')
$('tr')
$('input')

However, these selectors select all the paragraph tags, every div element, table rows, or input boxes on the page. If we want to select a specific paragraph tag or div element we must specify which one using the same methodology that CSS uses by using id and class names. The element's id can be selected by using the hash symbol # like the example below:

$('#pId p')

Which search's the current DOM (Document Object Model) and looks for a paragraph tag containing the id pId. So in this case the above example would select a paragraph tag that looks like this:

<p id="pId">some text here</p>

It is important in your coding to try to make id's unique. In other words, hopefully you will only have one paragraph tag on your page with this id. If you have another id named pId it will still work but you may confuse the two so it is better to name your id's and classes uniquely to avoid naming conflixts.

Just like id's you can select class elements in the DOM by passing a string consisting of a period symbol . like the example below:

$('.someClass') or if you want to me more specific $('table.someClass')

By specifying the element type before the period symbol you are narrowing down your selection to only the element with class "someClass" rather than all elements with class "someClass". Similar to CSS you can add parent container selectors to narrow the selection even further. An example of this would be:

$('div.testClass span')

Which, if you can guess selects all span elements inside of div elements with class "testClass".

No comments:

Post a Comment