GTM - Table - Press a button to extract the text from a different element

I am not a coder, but I'm diving into the world of Google Tag Manager with the aim of tracking button clicks on search results. I have clients who want to monitor interactions with specific products displayed in their search results. While setting up the basic button tracking in GTM is straightforward, I'm facing a challenge in associating each button click with its respective product name.

Here's a snippet of the HTML I'm focusing on:

    <tr>
    <td>
        <p class="category">
                Product 
        </p>
            <a href="/sector/product/123456789"><img class="search_image" src="https://example.com/medium/123456789.jpg" alt="Name of the Product" onerror="this.src='system/images/company_logo_block.jpg'" /> 
             </a>
    </td>
    <td>
        <h3><a href="/sector/product/123456789">Name of the product</a></h3>
        <p>Benefits of the product explained</p>
        <p>Material <b>Plastic</b></p>
        <div class="button_container">
            <div class="action_container">
                <div class="action_trigger">
                    <input type="hidden" id="code_123456789" name="code" value="123456789" />
                    <label class="visible" for="quantity_123456789">Quantity</label><br />
                    <input class="search_result_quantity numeric_only" id="quantity_123456789" name="quantity" type="number" value="1" 
                        onkeydown="return isValidInput(this, 5, event);"/>
                    <label for="add_to_basket_123456789">Add to basket</label>
                    <input class="add_sample search_result_action" id="add_to_basket_123456789" name="add_to_basket" type="submit" value="Add to basket" />
                </div>
                <div class="action_response">
                    <img src="/sector/system/images/loading.gif" alt="Loading" />
                </div>
                <div class="action_result">
                    <img src="/sector/system/images/tick.jpg" alt="Success" /><span>Added.</span><a href="/sector/basket/">View basket</a>
 </div>
<label for="get_sample">Get a Sample</label><input class="add_sample search_result_action" name="Sample_product" type="button"  value="Sample Product" onclick="window.location='http://www.samplepage.com/123456789';"/>
                <div class="clearer"></div>
            </div>
        </div>
        <br/>
        <p123456789</p>
        <p>
            Online
             &#124; 24/09/2015
        </p>
        <p><strong>Price:&nbsp;&nbsp;&pound;26.99  +VAT</strong></p>
    </td>
</tr>

My goal is to capture the product name, displayed within the <h3> tag in the corresponding <tr>, when a user clicks on the "Sample Product" button. Each product has its own set of details located within a dedicated <tr>.

While using document.querySelectorAll("tr td h3)[0] - or [1], or [2] allows me to access the correct nodes based on the product name, I can't figure out how to create a function that will return the text of the <h3> element upon clicking the button. Is this feasible?

Any assistance you can provide would be greatly appreciated. Sincerely, George

Answer №1

After numerous hours of experimenting and testing, I finally came across a successful solution that resolved my issue. I wanted to share it here in case it proves useful to someone else.

function() {
var elements = document.querySelectorAll('[value="Sample Product"]'); 
for (var j = 0; j < elements.length; j += 1) { 
if (elements[j] === {{Click Element}}) { 
    var elementName = document.querySelectorAll('tr td h3')[j].innerText
return elementName; }
}
return elementName;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The component "MeteorJS Collection" has not yet been initialized

superpack is an npm package that has been integrated using _wrapAsync. When attempting to insert into the collection UserSession, an error occurs indicating that the collection is undefined. server/helpers/b.js // Initialization var SUPERPACK = Meteor.re ...

The data in Next.js getStaticProps does not update or refresh as expected

As I recently transitioned to working with Next.js, I have encountered several challenges. One issue that arose was related to the use of useEffect in React compared to its behavior in Next.js. In my index file, I have implemented the following code: impo ...

Ways to verify the data type of a column in a table

I am currently working on making a table configurable. To achieve this, I am creating a demo component that will allow me to build my own customizable table. I intend to pass certain parameters to my table such as column names and data. The column names s ...

Disabling Navigation with Arrow Keys in Prettyphoto

Is there a way to prevent arrow keys from functioning in PrettyPhoto for a specific instance? I have tried using keyboard_shortcuts:false, but it still reloads the frame if left or right arrow keys are pressed, causing the form inside to reset. However, co ...

The font size appears significantly smaller than expected when using wkhtmltoimage to render

I am trying to convert text into an image, with a static layout and size while adjusting the font size based on the amount of text. I prefer using wkhtmltoimage 0.12.5 as it offers various CSS styling options. Currently, I am working on a Mac. Below is a ...

The loop is being controlled but the data is not being added and shown in the HTML div

I am struggling to display JSON data in an HTML div using a for loop. While my control is entering the loop, the data is not being appended and displayed in the HTML div. Here is the JSON data: [{"id":"15","FirstName":"ranjan","MiddleName":"","LastName": ...

Is there a way to identify the browser version that is being used?

I've been on the lookout for a specific code snippet that can help me identify whether the user visiting my website is using Firefox 3 or 4. Thus far, I have only come across code to determine the type of browser without indicating the version. Is th ...

What could be causing my difficulty in locating an HTML element using jQuery/JS string interpolation?

In my project, I have a set of div blocks each identified by a unique numerical id. For instance: https://i.sstatic.net/lYod8.png One of the tasks in my project is to select the 29th element following a specific chosen element. For example, if I choose t ...

Is there a way for a Vue component to interact with a button or checkbox in order to dynamically update tooltip content and button style using a function?

Is it possible for a Vue component to trigger button clicks or checkbox checks in order to update tooltip text and button color using a function? Despite the presence of a handle() function in the code provided, these changes are not currently taking effec ...

Instructions for adding a unique custom external CSS link, such as Bootstrap CSS, to a specific REACT component

Is it possible to incorporate custom CSS from the Bootstrap website into a React component? Since this CSS file cannot be imported directly, what steps should I take to include it? <link href="https://getbootstrap.com/docs/4.5/dist/css/bootstrap. ...

Unable to access account due to login function malfunctioning

I've created a login button with this function code, but I keep getting the error message "Login unsuccessful, Please try again..." Thank you in advance. I wasn't entirely sure what you needed, so I included most of the code because I've b ...

A variety of negative () DOM Selectors

I've been trying to select a specific node using two not clauses, but so far I haven't had any luck. What I'm attempting to achieve is selecting an element whose div contains the string 0008, but it's not 10008 and also does not contain ...

Remove the default selection when a different option is chosen using Bootstrap

I have implemented the Bootstrap-select plugin () for a multiple select dropdown on my website. Upon page load, there is a default option that is already selected. See image below: https://i.stack.imgur.com/SzUgy.jpg <select id="dataPicker" class=" ...

AJAX request stops functioning once the page is reloaded

As a beginner in JavaScript, I am facing an issue with my AJAX call. I have set up the call to process a back-end function when a button is clicked and expect to receive a response once the function is completed. However, whenever I refresh the page whil ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

Stop the child component from activating the parent's onClick event

Trying to implement Material-ui within a React project, I am facing an issue with the <IconButton> component and its onClick behavior conflicting with the parent component's behavior. Specifically, I want the <IconButton> to add an item to ...

Embedding a stylesheet into an HTML document can be done automatically

Currently, I am working on creating standalone error pages (404/503) as individual HTML files. My server-side setup involves Node.js, but these specific files will be hosted directly in Nginx. One of the challenges I am facing is automatically including a ...

Creating a flexible route path with additional query parameters

I am facing a challenge in creating a unique URL, similar to this format: http://localhost:3000/boarding-school/delhi-ncr However, when using router.push(), the dynamic URL is being duplicated like so: http://localhost:3000/boarding-school/boarding-school ...

Move the sprite to the center bottom of the orthographic camera

Looking for help positioning sprites at the bottom center of the orthographic camera. Here is the current setup - The object: function Obj() { const texture = useLoader(THREE.TextureLoader, loadedimg); const spriteRef = useRef(); return ( < ...

How do I send events between router view components in Vue.js?

I'm currently developing an e-commerce platform utilizing vue.js with a backend API. The root component is named Main.vue, consisting of a navigation section using router-link and a main content area displayed by router-view. Within the Cart.vue rout ...