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 搜索直系子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:querySelector 搜索直系子级


- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01