如何判断一个jQuery节点是否位于其父节点的开头?

问题描述:

考虑下面的HTML:如何判断一个jQuery节点是否位于其父节点的开头?

<p><img id="one" alt="at beginning, return true" />Some Text</p> 
<p>Some <img id="two" alt="in middle, return false" />Text</p> 
<p>Some Text<img id="three" alt="at end, return false" /></p> 

我怎么能告诉$("img#one")在其父节点的开始?

理想的情况是我想要做的是这样的:

$("p>img").each(function() { 
    var $this = $(this); 
    var $parent = $this.parent(); 
    if ("$this is at the beginning of $parent.html()") { 
     $parent.before($this); 
    } else { 
     $parent.after($this); 
    } 
}); 

编辑:sebasgo's help,这里的最终代码和结果:

$("p>img").each(function() { 
    var $this = $(this); 
    var $parent = $this.parent(); 
    if (this == this.parentNode.firstChild) { 
     $parent.before($this); 
    } else { 
     $parent.after($this); 
    } 
}); 

<img id="one" alt="at beginning, return true" /> 
<p>Some Text</p> 
<p>Some Text</p> 
<img id="two" alt="in middle, return false" /> 
<p>Some Text</p> 
<img id="three" alt="at end, return false" /> 

使用

var elem = $("img#one").get(0) 
if (elem.parentNode.firstChild == elem) 
{ .... } 

希望这个效果更好。

+0

我刚刚试过:第一胎,3例都是如此。 – travis 2009-07-17 16:46:18

+1

正如我看到jQuery忽略其选择器引擎中的文本节点。然后你可以使用普通的javascript: var elem = document.getElementById(“#one”); if(elem == elem.parentNode.firstChild){...} – sebasgo 2009-07-17 16:54:32

尝试这种情况:在SO

($parent.contents().eq(0).attr("id") === $this.attr("id")) 

从类似的问题。

How to match first child of an element only if it's not preceeded by a text node?

$("p>img").each(function() { 
    var prev = this.previousSibling; 
    var isThisTheFirstNode = $(this).parent().html().toUpperCase().indexOf('<IMG>') == 0; 

    var method = isThisTheFirstNode ? 'before' : 'after'; 
    $(this).parent[method].before(this); 
}); 

下面的代码会告诉你,如果有问题的节点是“第一个孩子”还是不那么应该为你工作。我刚刚与类似的问题作斗争,这对我有用。

if($(this).prev().length) 
{ 
    // Not first-child 
} else { 
    // is first-child 
}