[英]How to chain selectors in Javascript without jQuery
While trying to manipulate the layout of external sites I am often forced to use a chain of selectors to target the specific element I want.在尝试操纵外部站点的布局时,我经常被迫使用一系列选择器来定位我想要的特定元素。 The first time I encountered this I was offered a jQuery solution and it is very easy to get results.第一次遇到这种情况时,我得到了 jQuery 解决方案,很容易得到结果。 I would prefer not to rely on jQuery and would like to know how feasible this is in standard Javascript.我不想依赖 jQuery 并且想知道这在标准 Javascript 中的可行性。 Here is an example jQuery 'chain' -这是一个示例 jQuery '链' -
$('div[id="entry"] > p[class="header"] > span[id="title"] > div[class*="entry"] > p[class="title"] > a[class*="target"]').. etc
So say the HTML structure is roughly所以说 HTML 结构大致是
<div id="entry">
<p class="primary">
<p class="header">
<span class="side">
<span id="title">
<div class="secondary entry">
<p class="return">
<p class="title">
<a class="img">
<a class="mytargetelement">
So how is this possible normally?那么这通常怎么可能呢? Thanks.谢谢。
Enter document.querySelectorAll .输入document.querySelectorAll 。
It's what jQuery uses internally for browsers that support it.这是 jQuery 在内部用于支持它的浏览器。 The syntax is the same as in jQuery (Sizzle) selectors, see Selectors API .语法与 jQuery (Sizzle) 选择器中的语法相同,请参阅选择器 API 。
This isn't pretty..这个不好看。。
For each nested/chained element you can get its children via childNodes property.对于每个嵌套/链式元素,您可以通过childNodes属性获取其子级。 And then let the looping commence.然后让循环开始。 :/ You'd then have to recursively loop through all children and children's children, and so on, until you find the appropriately matched element(s). :/ 然后你必须递归循环遍历所有子元素和子元素,依此类推,直到找到适当匹配的元素。
Updated :更新:
To check for part of class name, you can do something like this:要检查 class 名称的一部分,您可以执行以下操作:
if (element.className.indexOf('myClass') >= 0) {
// found it!
}
If you want to avoid jQuery and only use complex CSS selectors then the SizzleJS library might be what you need.如果您想避免 jQuery 并且只使用复杂的 CSS 选择器,那么SizzleJS 库可能就是您所需要的。 It's a lot easier than doing it yourself every time you're looking for a DOM element!这比每次查找 DOM 元素时都自己做要容易得多!
function selectors(){
var temp= []; //array for storing multiple id selectors.
for(var i = 0;i<arguments.length;i++){
if(typeof arguments[i] === 'string')
temp.push(document.getElementById(arguments[i]));
}
return temp; //for chanining
},
now call the function as many time as you want like
selectors('p').selectors('anyid')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.