2

私はこれに苦労しています。

<div>クラスや ID を持たないテキストを新しい要素で囲むにはどうすればよいですか?

以下はシナリオです。

<div class="ContentDiv">.....</div>

Share your knowledge. <a href="URL">Be the first to write a review »</a>

" "divをラップする新しいものが必要ですShare your knowledge. <a href="URL">Be the first to write a review »</a>

私は次のことを試しました:

$(document).ready(function() {
  $('.ContentDiv').each(function() {
    $(this).add($(this).next()).wrapAll('<div class="NewDiv"></div>');
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ContentDiv">.....</div>

Share your knowledge. <a href="URL">Be the first to write a review »</a>

ただし、要素のみをラップし、その<a>下にテキストを残すため、機能していません。そこに残りのテキストも必要です。

4

2 に答える 2

4

次のテキストノードを取得して.ContentDivラップする必要があります。

$('.ContentDiv').each(function() {
   $(this).next('a').add(this.nextSibling).wrapAll('<div class="NewDiv"></div>');
});

フィドル

jQuery は実際にはテキストノードを取得しないため、ネイティブが機能するnextSiblingはずです。

于 2013-02-15T18:03:04.373 に答える
0

このために、$('.ContentDiv') の後に div を追加し、そこに html を追加できます。

$("<div id='new_div'></div").insertAfter($('.ContentDiv')).html("Share your knowledge. <a href='URL'>Be the first to write a review »</a>");
于 2013-02-15T18:09:27.213 に答える