简体   繁体   中英

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}}  }) 
});

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}}  }) 
});

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM