How to get the Previous Sibling name

后端 未结 2 1342
感动是毒
感动是毒 2021-01-21 06:18

I need to get the name of the previous sibling . to keep it simple i have some sample code



 
   

        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-21 06:54

    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.

提交回复
热议问题