How to get the Previous Sibling name

£可爱£侵袭症+ 提交于 2019-12-02 02:26:25

Using jQuery it would be:

$('#item2').prev().attr("name")​​​​​​​​​​;​

With regular javascript you would need to use the following function (to ensure whitespace nodes are ignored)

getPreviousSiblingName(document.getElementById("item2"))

function getpreviousSiblingName(element) {
    var p = element;
    do p = p.previousSibling;
    while (p && p.nodeType != 1);
    return p.attributes["name"].value;
}

That's because more likely your previousSibling will be a text node and not an element node. You need previousElementSibling (where supported) or a loop that will get the previousElement until the nodeType will be 1 (Node.ELEMENT_NODE).

In addition, name is not applying to p element (see https://developer.mozilla.org/en/DOM/Element.name) it could be better if you use a custom attribute (like an HTML5 data-* attribute, in your case data-name maybe) and therefore use dataset to get the attribute's value, or a generic getAttribute.

Of course library like jQuery can help to abstract all those things, the explanation is related to just vanilla JavaScript.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!