2

重複の可能性:
jquery-子テキストのない要素のテキストを取得します

私は内部にテキストがあり、次のようなテキストの後にスパンするdivを持っています:

<div>
text
<span>other text</span>
</div>

スパンではなくdivのテキストのみを取得したい

ありがとう

4

3 に答える 3

1

これを試して

  var myText = $('#dd').clone()            
             .children()    //select all the children
             .remove()  //remove all the children
             .end() //again go back to selected element
             .text();   //get the text of element
于 2012-10-03T10:26:24.710 に答える
0

そのために.clone()を次のように使用できます。

b = $('div').clone();
b.children('span').remove();
alert( b.text() ); // alerts "text"

を使用.clone()すると、ページに表示されている元のDOM要素に影響を与えることなく、divのコピーを作成し、スパンを削除してから、テキストを取得できます。

于 2012-10-03T10:24:40.537 に答える
0
var theText = "";
$('div').contents().each(function() {
    if(this.nodeType === 3) theText += $(this).text();
});
于 2012-10-03T10:15:36.617 に答える