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 搜索直系子级
基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
