[英]How can I tell if a jQuery node is at the beginning of its parent node?
Given the following HTML: 给出以下HTML:
<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>
How would I be able to tell that $("img#one")
is at the beginning of its parent node? 我怎么能告诉$("img#one")
是否在其父节点的开头?
Ideally what I'm trying to do is this: 理想情况下,我正在尝试做的是:
$("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);
}
});
Edit: with sebasgo's help , here's the final code and result: 编辑:在sebasgo的帮助下 ,这是最终的代码和结果:
$("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" />
Use 采用
var elem = $("img#one").get(0)
if (elem.parentNode.firstChild == elem)
{ .... }
Hope this works better. 希望这更好。
The following code will tell you if the node in question is the 'first-child' or not so should work for you. 以下代码将告诉您相关节点是否是“第一个孩子”,因此应该适合您。 I've just been battling with a similar problem and this worked for me. 我一直在与类似的问题作斗争,这对我有用。
if($(this).prev().length)
{
// Not first-child
} else {
// is first-child
}
试试这个条件:
($parent.contents().eq(0).attr("id") === $this.attr("id"))
From similar question on SO. 来自SO的类似问题。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.