I’m trying to create an event listener to capture the Store Name from the first strong
tag when a user clicks the Get Directions link, in order to pass the value to the GTM datalayer.
Is it a good approach to use an if statement on click to check for the directions
class, then look for the closet li
and then somehow drill down to the first strong
tag?
I don’t have the ability to easily alter the HTML as it’s a WordPress plugin.
<li id="7245">
<div class="store-location">
<p>
<strong>Store Name</strong>
<span>Store Street</span>
<span>Store Town</span>
<span>Store Country</span>
</p>
<p class="contact-details">
<span>
<strong>Email</strong>: <a href="mailto:[email protected]">[email protected]</a>
</span>
</p>
</div>
<div class="direction-wrap">
19 mi
<a class="directions" href="#">Get Directions</a>
</div>
</li>
I tried creating the event listener but was unable to get the right syntax for the if statement and I don’t have the knowledge of JS to know how to track the click and find the value I need to capture.
2
Answers
You can get the
e.target
from the event, and use.closest
to get theli
, and then use.querySelector
to get the element you care about:Since the outer
<li></li>
tag is not corrupted, you could use the ‘innerHTML’ attribute to get the content as a string, then search for the first appearance of<strong>
in the string and get the value from there:should get you the result ‘Store Name’.
docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
EDIT: i just realized you wanted an event handler to do this, so, borrowing from dave’s excellent approach above, maybe try something like this: