Ways to retrieve the inner text of a sibling element

Within GTM, I am attempting to retrieve the inner text of a sibling element when the clicked element is triggered.

<div class="repair-item-n ">
  <div class="repair-slide--54894d33-6c88-488f-95d7-3ec9b6a3ade4">
    <div class="restoration_wrap text-center">
      <img class="restoration-image">
    </div>
    <p class="title">Bags</p>
  </div>
</div>

For instance, upon clicking on the "restoration-image" class, I want to retrieve the value "Bags".

Since there are multiple instances of this HTML structure on the page with variations like "Shoes", "Hats", etc., I aim to identify and return the respective text of the "title" class upon each click event.

Answer №1

Here's a suggestion for you:

let imageList = document.querySelectorAll('.restoration-image');

imageList.forEach(function (img) {
    img.addEventListener('click', function (event) {
        let parent = this.parentNode;
        let nextSib = parent.nextElementSibling;

        alert(nextSib.innerText);
    });
}); 

Answer №2

Here is a solution tailored for GTM custom JavaScript variables.

function retrieveAlternateText() {
  if({{event}} === 'gtm.click') {
    var img = {{Click Element}};
    var parentElement = img.parentNode,
        nextEl = parentElement.nextElementSibling;
    return nextEl.innerText;
  }
}

Answer №3

To accomplish this task, I suggest utilizing a Custom JavaScript Variable:

Click - Retrieve Repair Item Title

function() {
  var clickedElement = {{Click Element}};
  if (!clickedElement) return;

  // Locate the common parent element
  var repairItemElement = clickedElement.closest(".repair-item-n");
  if (!repairItemElement) return;

  var titleElement = repairItemElement.querySelector(".title");
  if (!titleElement) return;

  return titleElement.innerText;
}}

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

How can I extract the JSON value as a string?

I have a scenario where I define two objects. The first object, BOB, has properties "name" with a value of "bob" and "height" with a value of 185. var BOB = { "name": "bob", "height": 185 }; The second object, PROPS, references the height property from ...

I'm stuck on finding the solution for PROJECT EULER P4

Challenge 4 Palindrome numbers read the same forwards and backwards. The largest palindrome that can be formed by multiplying two 3-digit numbers is 9009 = 91 × 99. Your task is to find the largest palindrome made from the product of two 3-digit numbers. ...

What is the best way to fetch the most recent article from every category using mongodb?

I am currently working with the following article schema: var articleSchema=new Schema({ id : Number, title : String, sefriendly : String, created : Date, categories: [ { id: Number, name: String, ...

What can be done to prevent unnecessary API calls during re-rendering in a React application?

On my homepage, I have implemented code like this: {selectedTab===0 && <XList allItemList={some_list/>} {selectedTab===1 && <YList allItemList={some_list2/>} Within XList, the structure is as follows: {props.allItemList.map(ite ...

Unable to target the first child of a specific class within the <select> element using CSS

Take a look at my fiddle: http://jsfiddle.net/augTa/ This is the snippet of my html code: <legend>Team Type</legend> <label>* Select Type :</label> <select name="team_type" style="width:150px;" id="team_type"& ...

Is there a way to remove all JavaScript files without touching the ones in the node_module folder?

How can I delete all the javascript files in a Node.js project, excluding those within the node_module directory, regardless of the operating system? I've attempted to achieve this using the `del-cli` npm package with the following script: del '* ...

Interactions between a service and a directive: interdependence or triggering of events

Issue: managing multiple directives that interact with a service or factory to communicate and log actions with a server. Should I establish dependencies between them? angular.module('someModule', []) .directive('someDir', ['l ...

Tips for retaining spaces in a multiline string when setting a helm value using cdktf

Currently, I am utilizing CDKTF to facilitate the deployment of the datadog helm chart into a kubernetes cluster. My objective is to assign a specific value to confd, however, the issue arises when the spaces in my typescript multiline string do not mainta ...

Executing prototype functions after a function has been defined

I'm looking to expand my knowledge on JavaScript prototypes. I came across some NodeJS modules where functions were being called in a chain like this: something.funcA().funcB().funcC(); and I want to implement something similar. How can I achieve this ...

Efficiently transferring property values

In my current code, I have functions that retrieve specific properties from an object within an array. Since each object in the array has multiple properties, I find myself using separate functions to extract different properties. This approach is not eff ...

Hide the scrollbars on the sidebar

I'm attempting to recreate a sleek scrollbar that caught my eye on the website . To achieve this, I need to have a screen larger than 955px in order to display the sidebar. However, when my sidebar overflows in the y direction, it causes an additional ...

Firebase: User interaction resulted in the closing of the popup before the completion of the operation. (auth/popup-closed-by-user)

I implemented a sign up with Google button using Firebase. When I click on it and choose an account, everything works fine. However, when I click on the exit button in the popup window, it crashes with the following error: "Firebase: The popup has been clo ...

I started off using Node.js with MongoDB, but now I want to switch to MySQL with Sequelize and implement async/await functions. However, I've run into a problem. Can

Can I use async await in JavaScript with Node.js Express and Sequelize to consult a table of products in an API? import { ProductoModel } from "../models/ProductoModel.js"; const listar = async (req,res) => { try { ...

`How to pass parameters to a function in Node.js`

I came across this code snippet : const { Logger } = require ("telegram/extensions"); const { TelegramClient } = require ("telegram"); const { StringSession } = require ("telegram/sessions"); const { NewMessage } = require (&q ...

Aligning a DIV using javascript

Hey everyone, I'm encountering an issue with the JavaScript on my website. I'm struggling to center the div in order to properly display the image I click on. It seems to work fine on the second attempt, but on initial click, the div always appea ...

What is the best way to perform calculations within a PHP loop for <input> elements and then display the results using a JavaScript loop?

Hello everyone, I'm currently struggling with displaying the calculations from a loop of input tags. What I'm trying to achieve is having 5 rows with input fields. At the end of each row, there should be a span area that displays the calculation ...

Getting the expanded row columns values in a RadGrid when using the onHierarchyExpanded event

Here is the code for my RadGrid: <telerik:RadGrid ID="ProductRanges_Grd" ShowHeaderWhenEmpty="true" runat="server" AutoGenerateColumns="false" Width="100%" Height="250px" ShowHeader="true" Visible="false" ...

The stubborn Node and Passport are refusing to update the password using user.setPassword

Currently, I am working on setting up my program to update a user's password only when the old one is confirmed as correct. Most of the code functions as expected except for one specific line: router.put("/:id/edit_password", isLoggedIn, isAdministra ...

Generate a dynamic form that automatically populates different input fields based on JSON data

I am trying to dynamically auto populate a form with various input types such as select boxes and text areas. I have successfully implemented this for input boxes, see example below: function autofill(){ var data = [{visible_retail: "0", brand: ...

The persistent problem with constantly polling the $.ajax request

One issue I'm facing involves a continuous polling $.ajax request. The challenge lies in initiating it immediately first, and then running it at intervals set in the setTimeout call. Take a look at the example code here. myObj = {}; var output = ...