javascript contents text - jQueryでテキストノードを選択するにはどうすればよいですか?
5
Answers
node children get
jQueryコレクションのように、要素のすべての子孫テキストノードを取得したいと思います。 それをする最善の方法は何ですか?
371 votes
javascript
jQuery.contents()
をjQuery.filter
とともに使用して、すべての子テキストノードを見つけることができます。 ちょっとひねりをかけて、孫のテキストノードも見つけることができます。 再帰は必要ありません:
$(function() {
var $textNodes = $("#test, #test *").contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
});
/*
* for testing
*/
$textNodes.each(function() {
console.log(this);
});
});
div { margin-left: 1em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
child text 1<br>
child text 2
<div>
grandchild text 1
<div>grand-grandchild text 1</div>
grandchild text 2
</div>
child text 3<br>
child text 4
</div>
javascript1
369
すべての子が要素ノードまたはテキストノードのいずれかであると仮定できる場合、これが1つの解決策です。
すべての子テキストノードをjqueryコレクションとして取得するには:
$('selector').clone().children().remove().end().contents();
テキストでない子要素を削除した元の要素のコピーを取得するには:
$('selector').clone().children().remove().end();
javascript2
368
このようにすることもできます:
var textContents = $(document.getElementById("ElementId").childNodes).filter(function(){
return this.nodeType == 3;
});
上記のコードは、特定の要素の直接の子の子ノードからtextNodesをフィルタリングします。
javascript3
367
私にとって、普通の.contents()
はテキストノードを返すように働いていましたが、あなたのセレクタがテキストノードであることを知るためにセレクタを注意する必要があります。
たとえば、これは私のテーブルのTDのすべてのテキストコンテンツをpre
タグでラップしても問題はありませんでした。
jQuery("#resultTable td").content().wrap("<pre/>")
javascript4
366