私はいくつかのjqueryのような機能を持っています:
function(elem) {
return $('> someselector', elem);
};
問題は、どうすれば同じことができquerySelector()
ますか?
問題は、親を明示的に指定する必要がある>
セレクターです。querySelector()
回避策はありますか?
私はいくつかのjqueryのような機能を持っています:
function(elem) {
return $('> someselector', elem);
};
問題は、どうすれば同じことができquerySelector()
ますか?
問題は、親を明示的に指定する必要がある>
セレクターです。querySelector()
回避策はありますか?
完全な答えではありませんが、IE を除くほとんどのブラウザー (デスクトップとモバイルの両方) で既に利用可能なW3C Selector API v.2に注目する必要があります (Edge はサポートしているようです):完全なサポート リストを参照してください。
function(elem) {
return elem.querySelectorAll(':scope > someselector');
};
できません。出発点をシミュレートするセレクターはありません。
jQuery がそれを行う方法 (さらに、qsa
彼らの好みに合わない振る舞いのため) は、ID があるかどうかを確認しelem
、そうでない場合は一時的に ID を追加してから、完全なセレクター文字列を作成することです。
基本的には次のようにします。
var sel = '> someselector';
var hadId = true;
if( !elem.id ) {
hadID = false;
elem.id = 'some_unique_value';
}
sel = '#' + elem.id + sel;
var result = document.querySelectorAll( sel );
if( !hadId ) {
elem.id = '';
}
これは確かに jQuery のコードではありませんが、私が覚えている限りでは、基本的にはこれらのコードが行うことです。この状況だけでなく、ネストされた要素のコンテキストからセレクターを実行しているあらゆる状況で。
avetiskがセレクター API 2に言及したように、:scope
疑似セレクターを使用します。
これをすべてのブラウザー (をサポートするquerySelector
) で機能させるには、次のポリフィルを使用します。
(function(doc, proto) {
try { // check if browser supports :scope natively
doc.querySelector(':scope body');
} catch (err) { // polyfill native methods if it doesn't
['querySelector', 'querySelectorAll'].forEach(function(method) {
var nativ = proto[method];
proto[method] = function(selectors) {
if (/(^|,)\s*:scope/.test(selectors)) { // only if selectors contains :scope
var id = this.id; // remember current element id
this.id = 'ID_' + Date.now(); // assign new unique id
selectors = selectors.replace(/((^|,)\s*):scope/g, '$1#' + this.id); // replace :scope with #ID
var result = doc[method](selectors);
this.id = id; // restore previous id
return result;
} else {
return nativ.call(this, selectors); // use native code for other selectors
}
}
});
}
})(window.document, Element.prototype);
node.querySelector(':scope > someselector');
node.querySelectorAll(':scope > someselector');
歴史的な理由から、私の以前の解決策
すべての回答に基づく
// Caution! Prototype extending
Node.prototype.find = function(selector) {
if (/(^\s*|,\s*)>/.test(selector)) {
if (!this.id) {
this.id = 'ID_' + new Date().getTime();
var removeId = true;
}
selector = selector.replace(/(^\s*|,\s*)>/g, '$1#' + this.id + ' >');
var result = document.querySelectorAll(selector);
if (removeId) {
this.id = null;
}
return result;
} else {
return this.querySelectorAll(selector);
}
};
使用法
elem.find('> a');
請求
個人的には、patrick dw から回答を受け取り、彼の回答に +1 を付けます。私の回答は、別の解決策を探すためのものです。私はそれが反対票に値するとは思わない。
これが私の試みです:
function q(elem){
var nodes = elem.querySelectorAll('someSeletor');
console.log(nodes);
for(var i = 0; i < nodes.length; i++){
if(nodes[i].parentNode === elem) return nodes[i];
}
}
http://jsfiddle.net/Lgaw5/8/を参照してください
調べている要素のタグ名がわかっている場合は、それをセレクターで使用して、目的を達成できます。
たとえば、 と を<select>
持つ が<option>
あり、 内の子ではなく、直接の子である<optgroups>
のみが必要な場合:<option>
<optgoups>
<select>
<option>iPhone</option>
<optgroup>
<option>Nokia</option>
<option>Blackberry</option>
</optgroup>
</select>
そのため、select 要素への参照を使用すると、驚くべきことに、次のように直接の子を取得できます。
selectElement.querySelectorAll('select > option')
Chrome、Safari、および Firefox で動作するようですが、IE ではテストされていません。=/
以下は、直接の子に対してのみ CSS セレクター クエリを実行するための単純化された一般的な方法です"foo[bar], baz.boo"
。
var count = 0;
function queryChildren(element, selector) {
var id = element.id,
guid = element.id = id || 'query_children_' + count++,
attr = '#' + guid + ' > ',
selector = attr + (selector + '').replace(',', ',' + attr, 'g');
var result = element.parentNode.querySelectorAll(selector);
if (!id) element.removeAttribute('id');
return result;
}
*** Example Use ***
queryChildren(someElement, '.foo, .bar[xyz="123"]');
それは私のために働いた:
Node.prototype.search = function(selector)
{
if (selector.indexOf('@this') != -1)
{
if (!this.id)
this.id = "ID" + new Date().getTime();
while (selector.indexOf('@this') != -1)
selector = selector.replace('@this', '#' + this.id);
return document.querySelectorAll(selector);
} else
return this.querySelectorAll(selector);
};
直接の子を検索する場合は、> の前に @this キーワークを渡す必要があります。
要素にIDがあるかどうかを確認し、そうでない場合はランダムなIDを追加し、それに基づいて検索を行います
function(elem) {
if(!elem.id)
elem.id = Math.random().toString(36).substr(2, 10);
return elem.querySelectorAll(elem.id + ' > someselector');
};
と同じことをします
$("> someselector",$(elem))