Search code examples
jqueryfacebookgoogle-tag-managerfacebook-pixel

(GTM) Get textContent of previousElementSibling within fb pixel standard event


I'm trying to have the text content of the closest html tag (with id) added to my facebook pixel standard event parameter. It should work with any html tag, I'd like it to be flexible whether if the text is within a div, span, p, or else.

Below is the jQuery I added to my GTM tag. Note that the {{Click Element}} is a native GTM variable. Also note that the GTM trigger I'm using to fire the GTM tag (so the below jQuery code) is set so the script is launched when clicking on the "buy" class (see HTML code).

<script>
  // look for the content_name
var presentElement = {{Click Element}};
var product_name_element = presentElement;
var cond = true;
while(cond){
    if(product_name_element.id=="product_name"){
        cond = false;
    }else{
        product_name_element = product_name_element.previousElementSibling;
    }
}
var product_name = product_name_element.textContent;
fbq('track', 'AddToCart', {
 content_name: product_name
});
</script>

And the HTML:

    <p id="product_name">Product 1</p>
    <p><a href="#" class="buy">Order</a></p>
    <p id="product_name">Product 2</p>
    <p><a href="#" class="buy">Order</a></p>
  • So basically, in my FB pixel event, I should have the following:
    • content_name: Product 1
    • when clicking the first Order link
  • and
    • content_name: Product 2
    • when clicking the second Order link.

Any help would be really pleased!

Many thanks.


Solution

  • In your case you need to create trigger:

    • Event type: Click - Just links
    • Click Element; matches css selector; .buy enter image description here

    Then create tag:

    • Tag type: Custom HTML
    • HTML

      <script> // look for the content_name var presentElement = {{Click Element}}; var product_name_element = presentElement.parentElement; var cond = true; while(cond && product_name_element!= null){ if(product_name_element.id=="product_name"){ cond = false; }else{ product_name_element = product_name_element.previousElementSibling; } } if (product_name_element != null) { var product_name = product_name_element.textContent; fbq('track', 'AddToCart', { content_name: product_name }); } </script>

    • Trigger - trigger defined above