user1663218
user1663218

Reputation: 1

Get contents of a clicked div

I have a string of divs with the same css class (.nav_div), with different text in each, in a navigation bar. They're set up like this:

<div class=nav_div>Contact</div>...

I set all those divs to enter a function when any is clicked, by this:

$('.nav_div').click(nav_is_clicked);

In the function nav_is_clicked(), I want to store the contents of the div that was clicked in a variable called div_text, but I'm having trouble. This did not work:

var div_text = $(this).contents().text();

How do I get the text from the div that was clicked?

Thanks.

Upvotes: 0

Views: 66

Answers (1)

Jason P
Jason P

Reputation: 27012

Just use text(). contents() gives you "the children of each element in the set of matched elements, including text and comment nodes.", which is not what you want.

$('.nav_div').click(nav_is_clicked);

function nav_is_clicked() {
    var div_text = $(this).text();
}

Edit -

It looks like your original code does actually work: http://jsfiddle.net/SLVEs/

Are you binding the click handler before the element exists (like before the page is loaded)?

Upvotes: 1

Related Questions