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.
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.
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.
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 .
your code seems to be correct, try this one too.
$('#my-div a').click(function(e) { var txt = $(e.target).text(); console.log(txt); });
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With