/ / Come faccio a racchiudere tutti i nodi di testo con <p> in un div che può contenere anche altri <p> ​​tag e tag come <strong> usando jQuery? - javascript, jquery, html

Come faccio a racchiudere tutti i nodi di testo con <p> in un div che potrebbe contenere anche altri tag <p> e tag come <strong> usando jQuery? - javascript, jquery, html

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 № 1

Penso 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