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

前端 未结 3 1883
孤独总比滥情好
孤独总比滥情好 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:08

    Does .previousSibling always return the parent's text node if it exists?

    No. It returns the immediately preceding sibling. In your case, there is a text node (a new line) immediately preceding the a element, so it returns that.

    If you remove the white space it should work as expected:

    <div>
        <input><a></a> <!-- input is immediately preceding anchor -->
    </div>
    

    However, that's not a particularly nice solution. See @Esailija's answer for a nicer one!

    0 讨论(0)
  • 2021-01-12 16:13

    According to http://www.w3schools.com/dom/prop_element_previoussibling.asp

    The previousSibling property returns the previous sibling node (the previous node in the same tree level) of the selected element

    If there is no such node, this property returns null.

    technically, what you're showing there is

    <div><textnode><input><textnode><a><textnode></div>
    

    ...so if the browsers are following the rules, it should keep working properly. If you're asking whether or not there are browsers out there that fail to follow the rules on this, I can't help you, but I will note that IE has a habit of adding dom objects to pages (particularly as wrappers) which might prove hazardous regardless.

    Edit: http://www.w3schools.com/dom/dom_nodes_navigate.asp has this to say on the topic.

    Firefox, and some other browsers, will treat empty white-spaces or new lines as text nodes, Internet Explorer will not.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题