Harry
Harry

Reputation: 1519

Get contents of div with inner div

HTML:

<div class="chocs">Chocolate Bar <div class="id">1234</div></div>

jQuery:

$('div#groupinfo .chocs').click(function(){
   alert($(this).slug.text());
});

Im trying to get the contents of the inner div (id) when the outer div is clicked. Can this be done?

Upvotes: 1

Views: 2907

Answers (4)

Asciiom
Asciiom

Reputation: 9975

Yes it's what jQuery is for (among other things of course). This solution uses the context parameter, it looks for elements with the class of idinside the element that was clicked on by providing thisas the context object.

$('div#groupinfo .chocs').click(function(){
    alert($(".id", this).html());
});

DEMO

Upvotes: 1

rahul
rahul

Reputation: 7663

you can do it with the help of find like this

$('div#groupinfo .chocs').click(function(){
   alert($(this).find('.id').text());
});

Jquery find method

Upvotes: 0

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91309

Assuming you have a parent div with the id groupinfo:

$('div#groupinfo .chocs').click(function() {
   alert($(this).find(".id").text());
});​

Upvotes: 1

Matt
Matt

Reputation: 75317

Use the children() method to target the child div;

$('div#groupinfo .chocs').click(function(){
   var contents = $(this).children('.id').text();
});

If the inner div ends up not-being-a-direct-child, use find() instead;

$('div#groupinfo .chocs').click(function(){
   var contents = $(this).find('.id').text();
});

Upvotes: 3

Related Questions