Reputation: 39
I'm working on a custom java script variable for tag manager to track the navigation of my page. The script is only working for the very first element of the kind because of document.queryselect. document.queryselectAll is naturally not solving the problem. It would be great if you could help me:
function(){
var elem = {{Click Element}};
var menu = document.querySelector("ul.nav.meta-nav.justify-content-end");
if(menu.contains(elem)){
return "nav_header";
};
var menu = document.querySelector("div.product-item");
if(menu.contains(elem)){
return "itemlist";
};
var menu = document.querySelector("a.btn");
if(menu.contains(elem)){
return "cta_button";
};
var menu = document.querySelector("footer.footer*");
if(menu.contains(elem)){
return "footer";
}
return "other";
}
Upvotes: 1
Views: 98
Reputation: 2372
function(){
var elem = {{Click Element}};
var type = "other"
var selectors = {
"ul.nav.meta-nav.justify-content-end" : "nav_header",
"div.product-item" : "itemlist",
"a.btn" : "cta_button",
"footer.footer *" : "footer"
}
for (const [key, value] of Object.entries(selectors)) {
var domMenu = document.querySelector(key)
if(domMenu && domMenu.contains(elem)){
type = value
};
}
return type;
}
Can not test from my end but it might work.
Just make sure the selectors is good and the click element should not fall into more than one selectors.
Upvotes: 0
Reputation: 19493
Element.querySelectorAll()
returns a NodeList. It's like an array. So a typical usage would be:
var elem = {{Click Element}};
document.querySelectorAll(selector).forEach(function(el) {
if (el.contains(elem)) {
return el.getAttribute("data-something");
}
})
Upvotes: 1