X10nD
X10nD

Reputation: 22030

I want to get the value of an id from a nested div - jquery

I want to obtain the .text() of #inner2

<div class="outer" id="outer">

<div id="inner1" class="inner">test1</div>
<div id="inner2" class="inner">test2</div>
<div id="inner3" class="inner">test3</div>


</div>

This is the jquery function I am using

$('.outer').bind('click',function() {


var one = $('#inner'+x).attr('id');
alert(one);


});

The problem is the first #id value is show in the alert.

Thanks

Jean

Upvotes: 0

Views: 2492

Answers (4)

rahul
rahul

Reputation: 187040

You can use .each to iterate through the divs with class name inner and then fetch the ids.

$('.outer').bind('click',function() {
    $("div.inner").each(function(){
        alert ($(this).attr("id"));
    });
});

If you want the id of the clicked one then use event.target

like

$('.outer').bind('click',function(e) {
    alert (e.target.id);
    alert($(e.target).text()); 
    // to get text wrap e.target to a jquery object and use .text() on that
});

Upvotes: 2

Gert Grenander
Gert Grenander

Reputation: 17084

If it's just to retrieve the inner2 on click:

$("#outer").click(function() {
  alert($("#inner2").text());
});

But if you actually are trying to get the text of the clicked inner div, then the following code will work:

$("#outer .inner").click(function() {
  alert($(this).text());
});

If it's to retrieve the ID, then just change text() to attr('id').

Upvotes: 0

bsboris
bsboris

Reputation: 639

$('.outer').bind('click',function() {


  var one = $('#inner2').text();
  alert(one);


});

Upvotes: 1

Jason Evans
Jason Evans

Reputation: 29186

$('.outer').bind('click',function() {

var one = $('#inner2').attr('id');
alert(one);

Upvotes: 2

Related Questions