简体   繁体   English

脚本返回页面上不存在的元素

[英]Script returns element that not exists on page

I have this function, that returns me path to el . 我有此功能,这使我返回了el路径。 However sometimes this function adds element that not exists on page. 但是有时此函数会添加页面上不存在的元素。 In this case: 在这种情况下:

<table>
<tr><td></td><tr>
</table>

path to td will look like table > tbody > tr > td . td的路径将类似于table > tbody > tr > td Whats the problem with this function? 此功能有什么问题?

function getDomPath(el) {
        element = el;
        if (!(el instanceof Element)) return;
        var path = [];
        while (el.nodeType === Node.ELEMENT_NODE &&  el.id != "jobs") {
            var selector = el.nodeName.toLowerCase();
            if (el.id) {
                selector += '#' + el.id;
            }
            else if(el.className){
                console.log(el.className);
                selector += '.' + el.className;
            }
            else {
                var sib = el, nth = 1, count = 1;
                while (sib.nodeType === Node.ELEMENT_NODE && (sib = sib.previousSibling)  && nth++){
                    console.log(Node.ELEMENT_NODE)
                    console.log(el.previousSibling);
                    console.log(el);
                    count += $(el).prevAll().size();
                };
                selector += ":nth-child("+count+")";
            }
            path.unshift(selector);
            el = el.parentNode;
        }
        return path.join(" > ");
    };

If the problem is the tbody element, you need to know that it's not your function that adds it but the browser itself. 如果问题tbody元素,则需要知道添加它的不是您的函数,而是浏览器本身。 Look at your page using Firebug or the Web Developer tools in chrome. 使用Firebug或chrome中的Web Developer工具查看您的页面。

Take a look at this SO answer . 看看这个SO答案

There is no problem with the function, it correctly uses all the elements that does exist. 该函数没有问题,它可以正确使用确实存在的所有元素。

A table element always has a tbody element if there are any rows for it. 如果有任何行,则table元素始终具有tbody元素。 The browser adds the tbody element even if you don't have any tag for it in the markup. 即使您在标记中没有任何标签,浏览器也会添加tbody元素。

The browser will create complete elements, even if your markup is incomplete or if it has left out optional tags. 即使您的标记不完整或遗漏了可选标签,浏览器也会创建完整的元素。 For example, the browser will create two rows in your table, because you used <td> instead of </td> when you tried to end the first row. 例如,浏览器将在表中创建两行,因为尝试结束第一行时使用了<td>而不是</td> It will implicitly end the first row, start a new row, and implicitly end that too. 它将隐式结束第一行,开始新行,也隐式结束。 The elements in your table will end up just as if you wrote your markup as: 表中的元素将最终结束,就像您将标记编写为:

<table>
  <tbody>
    <tr>
      <td></td>
    </tr>
    <tr>
    </tr>
  </tbody>
</table>

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

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