Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the text value of a clicked link?

I have matching text in different parts of a document. The first is a set of "tags" in a table like so:

<div id="my-div">   <div><a href="#">tag 1</a></div>   <div><a href="#">tag 2</a></div> </div> 

Then in several other parts of the document, I have a hidden element after the items I want to highlight when the matching link is selected like so:

<div class="hide-me">tag 1</div> 

Then my click function is like this:

$('#my-div a').click(function() {   var txt = $(this).text();   console.log(txt); }); 

The output is an empty string, but I’m not sure why.

like image 867
95slug Avatar asked Feb 02 '11 06:02

95slug


People also ask

How to get text of clicked anchor tag in jQuery?

Method 1 - Retrieve the exact value of the href attribute:Select the element and then use the . getAttribute() method. This method does not return the full URL, instead it retrieves the exact value of the href attribute.

How to make a div a clickable link?

We simply add the onlcick event and add a location to it. Then, additionally and optionally, we add a cursor: pointer to indicate to the user the div is clickable. This will make the whole div clickable.

Can I give id to anchor tag?

The id and name attributes share the same name space. This means that they cannot both define an anchor with the same name in the same document. It is permissible to use both attributes to specify an element's unique identifier for the following elements: A , APPLET , FORM , FRAME , IFRAME , IMG , and MAP .


2 Answers

your code seems to be correct, try this one too.

$('#my-div a').click(function(e) {   var txt = $(e.target).text();   console.log(txt); }); 
like image 101
Umair Jabbar Avatar answered Sep 21 '22 02:09

Umair Jabbar


In your case I wouldn't use the text of the link, as it's possible it may change in the future (ie. you need to translate your website). The better solution is to add custom attribute to links:

<div id="my-div">   <div><a href="#" sectionId="someId1">tag 1</a></div>   <div><a href="#" sectionId="someId2">tag 2</a></div> </div> 

And then put the id of the hidden tag there, so you and up with:

$('#my-div a').click(function() {   var sectionId = $(this).attr('sectionId');   $('#' + sectionId).show();   return false; // return false so the browser will not scroll your page }); 
like image 23
Jakub Konecki Avatar answered Sep 20 '22 02:09

Jakub Konecki