A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

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

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.

This entry was posted in General and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

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