Does .previousSibling always return the parent's Text node first?

前端 未结 3 1902
孤独总比滥情好
孤独总比滥情好 2021-01-12 15:40

I\'m stuck using native DOM methods (I know, right?) and I have a structure like this:


3条回答
  •  长发绾君心
    2021-01-12 16:16

    It returns the previous sibling node, it might be text node, it might be element node, it might be null

    You can retrieve previous element nodes with .previousElementSibling which isn't supported in legacy browsers but you can use a function like:

    function previousElementSibling( elem ) {
    
        do {
    
            elem = elem.previousSibling;
    
        } while ( elem && elem.nodeType !== 1 );
    
        return elem;
    }
    

    previousElementSibling(this) will result in the input element.

提交回复
热议问题