In this discussion, we will learn how to select the best selector expression for our web application. jQuery is powerful of cascading style sheet and XPath selectors, so we can access elements or groups of elements in the Document Object Model ( DOM ) very quickly and easily. Other features of jQuery, it’s most powerful to make DOM traversal. In the previous discussion, we discussed basic learning jQuery, how jQuery works, access element or groups of elements in the DOM and how to manipulate it.

We can use type of selector in the jQuery code : CSS, XPath and Custom, but we always start with the dollar sign and parentheses: $(). The dollar sign ( $ ) is simply shorthand for jQuery, because $() function is very common in JavaScript libraries. So, we must ensure that the dollar sign not cause conflict with other JavaScript libraries in our web pages.

jQuery support most of the selectors included in CSS specification 1 – 3, see more detail about it at the World Wide Web Consortium’s site. With this features allow web developer to create application without worrying about which modern browsers might not understand advances selectors, as long as the browsers have JavaScript enabled. See more detail about how to selection element of the DOM with CSS selector with following code bellow.

1
2
3
4
5
6
7
8
 
	/* with this selector, 
            jQuery select all elements with tag name of div */
	$(‘div’) 
 
	/* with this selector, 
            jQuery select all elements with tag name of em  */
	$(‘em’)

With the selector above, jQuery uses JavaScript’s getElementsByTagName() function for tag name selector.

XPath selector expressions provide an alternative way to access DOM elements. XPath was developed as a selector language for XML documents and jQuery make a basic subset of it’s selectors available for use in XML and HTML documents. For more detail and information about XPath, visit the World Wide Web Consortium’s site. For example, following code use XPath selector.

1
2
3
4
5
6
7
8
 
	/* select all elements matched by <code> and 
	    Descendant of an element matched by <div> */
       $(‘div//code’)
 
       /* select all elements matched by <a> and  
           descendant an element matched by <p> */
      $(//p//a’)

For more information about each selector above at next discussion in this site.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • Slashdot
  • Technorati
  • YahooMyWeb