Given the following 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?
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:
$("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" />