user2647092
user2647092

Reputation: 397

How do I get the text of a tag

I am trying to grab the text of the that was clicked. I have a case where two different links are defined under teh same class and I need to identify which of the links was clicked

<div class="block pdp-estimate-quote">
  <ul>
    <li>
        <a href="#">Estimate Payment</a>
    </li>
    <li>
        <a href="#">Get a Quote</a>
    </li>
  </ul>
</div>

And I want to throw a GA event when someone clicks either link using the link text as the description. The following code throws an event but it shows the text for both links instead of just the one that was clicked.

$('.pdp-estimate-quote a').click(function(){ 
    var ctatext = $(this).closest(".pdp-estimate-quote").find('a').text();
    dataLayer.push({ 'event':'event', 'eventCategory': 'Get Quote', 'eventAction':ctatext, 'eventLabel':{{url path}}  }) 
});

Upvotes: 0

Views: 101

Answers (3)

Rory O&#39;Kane
Rory O&#39;Kane

Reputation: 30428

In event handlers, this refers to the element on which the event was fired. So in a click handler, this is the DOM element that was clicked.

var ctatext = $(this).text();

Upvotes: 1

epascarello
epascarello

Reputation: 207557

Because you are looking at the parent element and not the clicked element.

var ctatext = $(this).closest(".pdp-estimate-quote").find('a').text();

should be

var ctatext = $(this).text();

Upvotes: 3

Claudio Redi
Claudio Redi

Reputation: 68440

I might be missing something on your question but in order to get the text of the current element you just need to do

var ctatext = $(this).text();

So the complete function would be

$('.pdp-estimate-quote a').click(function(){ 
    var ctatext = $(this).text();
    dataLayer.push({ 'event':'event', 'eventCategory': 'Get Quote', 'eventAction':ctatext, 'eventLabel':{{url path}}  }) 
});

Upvotes: 5

Related Questions