How to select elements from inside jQuery objects

Thursday, April 16th, 2009 at 10:03 am by Maja Williams

I just came across a very interesting question in the jQuery Google group asking about how to select elements that are inside of a jQuery object. After posting my response there I thought I would follow it up with a new jQuery article.

Say for example we wanted to select the following block of XHTML:

Hello
blank
Hello

We would use jQuery to select this code black as follows with a bit of JavaScript:

(function ($) {
    $().ready ( function () {
        var main = $('#main');
    });
})(jQuery);

So when the above snippet runs it would select the element with the id of “main” in this case it’s the main div element. So then to further drill down to be able to select elements within this jQuery object we would extend the previous snippet to the following:

(function ($) {
	$().ready ( function () {
		var main = $('#main');
		main.each ( function () {
			var odds = $(this).find ('.odd');
			odds.each ( function () {
				$(this).append ('
World
'); }); }); }); })(jQuery);

Doing this will select all of the elements with the class “odd” and append two div’s to it. Obviously you could just select all of the “odd” elements in this document and get the same result but if you where working with multiple tables with the same class names and you only wanted to manipulate one this would be a useful technique.

Hope this helps. For further information about selectors please read my article jQuery selectors and attribute selectors reference and examples.

Share this article:
  • Digg
  • del.icio.us
  • Ping.fm
  • LinkedIn
  • Facebook
  • Sphinn
  • Mixx
  • Google Bookmarks
  • NewsVine
  • Reddit
  • Technorati
  • Slashdot
  • Netvibes
  • StumbleUpon
  • Live
  • Netvouz
  • Faves
  • Gwar
  • MySpace
  • Yahoo! Buzz

Tags: , , ,

Categories: Articles, Blogs, JavaScript, Technical, jQuery

Maja Williams has written 12 articles.

Other articles by this author Maja Williams

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>