jQuery: A quick and dirty tutorial on DOM traversing using parent() and classname selectors

Posted on: Dec 16, 2008 by wenbert

Here is a quick tutorial on DOM traversing using jQuery. I am using class selectors $(‘.classname’) here.

<div class="dynamically_created_div">
    <input type="button" class="click_button" id="click_button_01" value="Click Me!" />
	<input type="hidden" class="hidden_stuff" value="First one!" />
</div>
<div class="dynamically_created_div">
    <input type="button" class="click_button" id="click_button_02" value="Click Me!" />
	<input type="hidden" class="hidden_stuff" value="Second one!" />
</div>
<div class="dynamically_created_div">
    <input type="button" class="click_button" id="click_button_03" value="Click Me!" />
	<input type="hidden" class="hidden_stuff" value="Third one!" />
</div>
< script >
$(document).ready(function(){
    $(".click_button").click(function(){
		alert($(this).parent().find(".hidden_stuff").val()); 
		//This means:
		//GO to parent tag (that is the div) then,
		//once in the "parent", FIND an element with a classname that 
		//is equal to "hidden_stuff"
	});
});
< /script >

I made my code this way because I wanted to have something that I can re-use when I dynamically create my divs using jQuery.
Having the $(this).parent() will enable to access the DOM of the newly created elements without specifying the element Ids.

If you have comments / suggestions, just put them below. I would love to hear your ideas on how you would do something like this using jQuery.


Subscribe to comments Comment | Trackback |
Post Tags: ,

Browse Timeline


Add a Comment


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> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!