- すべての
<br>
ノードを取得します。<p>
必要に応じて、ブロック内に直接あるものを無視します。
- 次に、ノードごとに
<br>
、その直前または直後のテキスト ノードをラップします。
- 最後に、
<br>
ノードを削除します。
このアプローチはネストを処理し、リンクやページ レイアウトなどを破棄しません。
コード:
$('.your_cms_container br').each ( function () {
if (this.parentNode.nodeName != "P") {
$.each ([this.previousSibling, this.nextSibling], function () {
if (this.nodeType === 3) { // 3 == text
$(this).wrap ('<p></p>');
}
} );
$(this).remove (); //-- Kill the <br>
}
} );
アップデート:
OPの質問を編集した後、私は彼の特定の状況に十分に対処していないことに気付きました. (私は上記のコードを使用して、ユーザースクリプトで大きな効果を上げています。)
彼はこれを変更したいと考えています:
<p> "Paragraph 1" <br />
<a href="http://xkcd.com/246/">Link, the first</a>
Line after single break.
<br /><br />
"Paragraph 2"
</p>
これに:
<p> "Paragraph 1" <br />
<a href="http://xkcd.com/246/">Link, the first</a>
Line after single break.
</p>
<p> "Paragraph 2" </p>
問題は次のとおりです。ネストされた要素 (存在する場合) またはイベント ハンドラー (存在する場合) を破棄したくない場合。
これには、次のアプローチを使用します。
- のようなセレクターで問題のある段落だけを取得し
p:has(br+br)
ます。隣接するセレクターがテキスト ノードを無視することに注意してください。この場合、まさにそうしたくないことです。
- 問題のある各段落の内容を 1 つずつループします。
- ステート マシンを使用して、それぞれに新しい段落を作成し、コンテンツ ノードを適切な
<br><br>
に移動<p>
します。
コードは次のようになります。jsFiddle で実際に動作しているのを見ることができます:
var badGraphs = $("#content p:has(br+br)");
var targetP = null;
var justSplit = false;
badGraphs.each ( function () {
var parentP = $(this);
parentP.contents ().each ( function (J) {
if (justSplit) {
justSplit = false;
// Continue the loop. Otherwise, it would copy an unwanted <br>.
return true;
}
var thisjNode = $(this);
var nextjNode = $(this.nextSibling);
if (thisjNode.is ("br") && nextjNode.is ("br") ) {
thisjNode.remove (); //-- Kill this <br>
nextjNode.remove (); //-- and the next
//-- Create a new p for any following content
targetP = targetP || parentP;
targetP.after ('<p></p>');
targetP = targetP.next ("p");
justSplit = true;
}
else if (targetP) {
//-- Move the node to its new home.
targetP.append (this);
}
} );
} );