次のようなテキスト文字列を含むdiv内のすべてのhtml要素の配列を作成したい
<p>some string</p>.
文字列を取得したくないので、配列アイテムを要素にします(この例では、pノードになります)。文字列がどうなるかは前もってわからないので、一致する文字列値を探すことができません。また、空のテキストノードが配列に含まれることも望ましくありません。
ありがとう!
$("#my_div *").filter(function()
{
var $this = $(this);
return $this.children().length == 0 && $.trim($this.text()).length > 0;
})
このバージョンでは、テキストを含む要素を含む親要素は返されず、最後のレベルの要素のみが返されます。
最速ではないかもしれませんが、StackOverflowのホームページでは非常にうまく機能します:)
カスタムセレクターは、次の場合に役立ちます。
jQuery.expr[':'].hasText = function(element, index) {
// if there is only one child, and it is a text node
if (element.childNodes.length == 1 && element.firstChild.nodeType == 3) {
return jQuery.trim(element.innerHTML).length > 0;
}
return false;
};
その後、あなたは単にこれを行うことができます:
$('#someDiv :hasText') // will contain all elements with text nodes (jQuery object)
$('#someDiv :hasText').get() // will return a regular array of plain DOM objects
私はあなたがそれらの中にテキストだけを持っている要素だけを選択しようとしていると仮定しています。
notおよび空のセレクターを使用して、空でない要素を取得できます。配列への変換は、getを使用して実現できます。
$("#theDiv > :not(:empty)").get();
上記のセレクターは、「theDiv」のすべての子要素を取得し、それらは空ではありません(つまり、子またはテキストのいずれかを持っています)。次に、一致したセットを配列に変換します。
内部にテキストがある要素のみが必要な場合、これは機能するはずです...
$("#theDiv > :not(:empty, :has(*))").get();
空白のある要素を取り除くには、フィルターを使用できます
$("#theDiv > :not(:has(*))").filter(function() {
return $.trim(this.innerHTML).length > 0;
}).get();
var array = [];
var divSelector = "div.mine";
$(divSelector).contents().each(function()
{
// If not an element, go to next node.
if (this.nodeType != 1) return true;
var element = $(this);
if ($.trim(element.text()) != "")
array.push(element);
});
array
は、テキストを含む要素の配列です。
dは、物事を検索するdivです。v
は空の配列
です。iは0から開始する必要があります。
$ .trimは、空白だけのノードを取得しないようにするために使用されます。
$("*",d).filter( function() {
return $.trim($(this).text()) != ""
} ).each( function() {
v[i] = $(this).text();
i++;
} );
v.push($(this))を使用することもできます...これは完全に私の心を滑らせたものです。
$(function() {
var array = new Array();
$("#testDiv *").each(function(x, el) {
if ($.trim($(el).text()) != '' ) {
array.push(el);
}
});
alert(array.length);
});
:containsセレクターを使用します。
var matches = new Array();
$('#start_point *:contains(' + text + ')').each(function(i, item) {
matches.push( item );
}