Ho l'esempio seguente html:
<div>
Wrap this text with p which also includes <strong>this</strong> and also <a href="">this</a>.
<h1>Heading 1</h1>
<p>Some other text</p>
Wrap this text with p which also includes <strong>this</strong> and also <a href="">this</a>.
</div>
il risultato desiderato utilizzando jQuery:
<div>
<p>Wrap this text with p which also includes <strong>this</strong> and also <a href="">this</a>.</p>
<h1>Heading 1</h1>
<p>Some other text</p>
<p>Wrap this text with p which also includes <strong>this</strong> and also <a href="">this</a>.</p>
</div>
risposte:
2 per risposta № 1Penso che potresti iterare sul contenuto del div e creare un gruppo di elementi da incartare come indicato di seguito
var $group = $();
$("div").contents().each(function () {
if (this.nodeType == 3 || !$(this).is(":header, div, p")) {
if (this.nodeType != 3 || this.nodeValue.trim()) {
$group = $group.add(this);
}
} else {
$group.wrapAll("<p />")
$group = $()
}
});
$group.wrapAll("<p />")
demo: Violino