简体   繁体   English

从HTML结构中的DIV树获取上部元素

[英]Get upper element from DIV tree in HTML Structure

I have HTML code for every widget like this: 我有每个小部件的HTML代码,如下所示:

html code HTML代码

How get name attribute of div data-tracker-id (=118DBA90ECB84E7BB9E7C07402F4B4B25CC0CD43818B92F8E0C26CA63C5F543D) when i'm clicking on class , for instance, "slick-arrow slick-prev"? 如何在点击课程时获取div data-tracker-id (= 118DBA90ECB84E7BB9E7C07402F4B4B25CC0CD43818B92F8F0E0C26CA63C5F543D)的名称属性,例如“slick-arrow slick-prev”? Making DOM Element with CSS-Selector doesn't work. 使用CSS-Selector创建DOM元素不起作用。

You will need a custom HTML tag for this, where you can write your own code, which looks up this information, relative to the clicked element, which can be referred as {{Click Element}}, when enabled within built-in variables. 您需要一个自定义的HTML标记,您可以编写自己的代码,在内置变量中启用时,相对于单击的元素(可以称为{{Click Element}})查找此信息。

You can do it using jQuery, with the parent() function , which traverses up to the specified parent element. 您可以使用jQuery和parent()函数来执行此操作,该函数遍历指定的父元素。 Eg 例如

var parent = $({{Click Element}}).parent('div[data-tracker-id]');

You can also simulate this functionality using vanilla JavaScript. 您还可以使用vanilla JavaScript模拟此功能。 One possible solution: 一种可能的方案:

    //define function
      var gtmGetClosest = function ( elem, selector ) {

        // Element.matches() polyfill
        if (!Element.prototype.matches) {
            Element.prototype.matches =
                Element.prototype.matchesSelector ||
                Element.prototype.mozMatchesSelector ||
                Element.prototype.msMatchesSelector ||
                Element.prototype.oMatchesSelector ||
                Element.prototype.webkitMatchesSelector ||
                function(s) {
                    var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                        i = matches.length;
                    while (--i >= 0 && matches.item(i) !== this) {}
                    return i > -1;
                };
        }

        // Get closest match
        for ( ; elem && elem !== document; elem = elem.parentNode ) {
            if ( elem.matches( selector ) ) return elem;
        }

        return null;

      };

    //use it
    var parent = gtmGetClosest({{Click Element}}, 'div[data-tracker-id]');

Custom function was based on this article . 自定义功能基于本文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM