Blog Select the Child Element Inside jQuery’s $(this)
August 4, 2013 Development, HTML, jQuery Social Share
My goal was to grab the contents of the href attribute, which was #my_container as shown below.
<span class="item"><a href="#my_container">Click Here</a></span>
<div class="my_container">
<p>Show this Text</p>
</div>
$('.item').click(function()
{
var target_section = $(this).children('a').attr('href');
target_section = target_section.replace('#', '');
$('.' + target_section).show();
}
$(this) represents our clicked item which has the class of .item. Using the children() method, we search for the a tag, and then select its href attribute. The target_selection variable now holds the value of the href attribute. I then used a string function called .replace() to remove the # from the link.
Now I’m able to use the target_selection variable to show the correct div through its class of .my_container by appending a period. We can also get the child element’s position or other attributes.