querySelector与querySelectorAll [英] querySelector vs. querySelectorAll
问题描述
在javascript中创建选择器时遇到了一些麻烦.
这是我的代码:
I have some trouble in creating a selector in javascript.
This is my code:
function __(selector){
var self = {};
self.selector = selector;
if(typeof selector == 'object'){
self.element = self.selector;
}else{
self.element = document.querySelector(self.selector);
}
// make a .css method to an element
self.css = function(propval){
return Object.assign(self.element.style,propval);
}
return self;
}
还有我的html文件
<script src="js/selector.js"></script>
<script>
window.onload = function(){
__('p').css({'color':'red'});
}
</script>
<p>Hello</p>
<p>World</p>
<p>John</p>
上面的代码只会在第一个< p>
元素中应用 .css方法
.这是因为我只使用了 querySelector
.因为 querySelector
仅选择找到的第一个元素.然后 querySelectorAll
选择找到的所有元素.但是,当我尝试将选择器更改为 querySelectorAll
时,它对我不再起作用.
The code above will only apply the .css method
in the first <p>
element. It's because I only used querySelector
. Because querySelector
only selects the first element found. And querySelectorAll
selects all elements found. But when I try to change my selector to querySelectorAll
It doesnt work for me anymore.
推荐答案
好吧,原因是 querySelectorAll()
返回所选元素的NodeList并将CSS分配给NodeList strong>效果不大
Well, the reason is querySelectorAll()
returns a NodeList of the selected elements and assigning CSS to a NodeList wouldn't make much of an effect
也就是说,从本质上讲,您需要一种方法来处理单个元素和多个元素的情况
That said, essentially you need a way to handle the case of a single element and a many in the same way
从我的头开始,一个简单的解决方案可能是始终在它们上使用一个数组或NodeList 和 forEach()
,因为两者都实现了此方法,例如所以:
From the top of my head, a simple solution could be to always use an arrays or the NodeList and forEach()
over them since both implement this method, like so:
function __(selector){
var self = {};
self.selector = selector;
if(typeof selector == 'object'){
self.elements = [self.selector];
}else{
self.elements = document.querySelectorAll(self.selector);
}
// make a .css method to an element
self.css = function(propval){
self.elements.forEach(function(element){
Object.assign(element.style, propval);
});
}
return self;
}
这篇关于querySelector与querySelectorAll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!