querySelector search immediate children(querySelector 搜索直系子级)
问题描述
我有一些类似 jquery 的功能:
I have some jquery-like function:
function(elem) {
return $('> someselector', elem);
};
问题是我怎样才能对 querySelector()
做同样的事情?
The question is how can i do the same with querySelector()
?
问题是 querySelector()
中的 >
选择器需要明确指定父级.有什么解决办法吗?
The problem is >
selector in querySelector()
requires parent to be explicitly specified. Is there any workaround?
推荐答案
完成:scope polyfill
作为 avetisk 有 提到 Selectors API 2 使用 :scope
伪选择器.
为了在所有浏览器(支持 querySelector
)中实现这一点,这里是 polyfill
Complete :scope polyfill
As avetisk has mentioned Selectors API 2 uses :scope
pseudo-selector.
To make this work in all browsers (that support querySelector
) here is the polyfill
(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');
<小时>
由于历史原因,我之前的解决方案
For historical reasons, my previous solution
基于所有答案
// 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');
这篇关于querySelector 搜索直系子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!