Bernhard
Bernhard

Reputation: 11

How to access text inside nested div using jQuery

I'm trying for a long time to access the content of a div by click it.

The structure is like this:

<div class="note" id="DYNAMIC_ID">
     <div class="headline">HEADLINE</div>
     <div class="content">Content</div>
</div>

I need something like this:

$(".note").click(function(){
    alert(this+".headline").text();
    alert(this+".content").text();
});

I hope someone can help me with this problem.

Upvotes: 1

Views: 274

Answers (2)

Mike
Mike

Reputation: 654

maybe this could be a solution:

$(".note").click(function(){
alert(".headline").html();
alert(".content").html();

});

or

$(".note").click(function(){
alert("#DYNAMIC_ID").html();

});

Upvotes: 0

Sampson
Sampson

Reputation: 268414

The second parameter of your selector is the context. In this case, we want the context to be the div that had been clicked, so we use the this keyword as the context.

$("div.note").click(function(){
  var headline = $(".headline", this).text();
  alert(headline);
});

You could also use the .find() method too:

var headline = $(this).find(".headline").text();

Upvotes: 2

Related Questions