0

In the following source code, is it possible to create a JavaScript function which detects if the clickable element is in a specific node with a certain attribute.

Example:

<button data-type="mybutton">
  <div class="mydiv">
    <img src="">
  </div>
</button>

The clickable elements could be the <img>, <div>, or <button> tags, all included in the <button class='mybutton"> parent node. How can I create the condition in Javascript?

Something like this?

element.closest("button:data-type[mybutton]")

Thank you

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
  • So, you want to list all children of the ` – StefanN Jul 25 '19 at 13:47
  • We have `Node.contains()` to check if a certain node is included inside another node. And we have `Element.matches()` to see if a certain node would match a specific selector string. But unless I interpret the question wrong, just `element.querySelector( 'button[data-type="mybutton"]' )` should return the element if it exists, else it returns null. – Shilly Jul 25 '19 at 13:51
  • I created the following JS function within Google Tag Manager: if ({{Click Element}}.querySelector("button[data-type='mybutton']") != null) { myvalue = "ok"; } else { myvalue = "notok" ; } It looks not properly working, and when I'm testing it with the Chrome Console : console.log({{Click Element}}.querySelector("button[data-type='mybutton']"));, I always have the value null when I'm click on the different element ( and – user6113111 Jul 26 '19 at 08:02

1 Answers1

0

How to check in Javascript if one element is contained within another

Using the Node.contains() method mentioned in the link above, you should be able to do this by iterating through all candidate buttons (from querySelectorAll() with the proper tag and data-type) and see which one contains the element you clicked.

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32