来自nodelist的查询选择器

时间:2018-04-21 03:33:02

标签: javascript

来自nodelist的查询选择器

最好的方法是什么,可以提高效率?

提前致谢

function querySelectorFrom(selector, elements){
  var all = document.querySelectorAll(selector);
  var temp = [];
  for(var i =0; i< elements.length;i++){
    if(Array.prototype.indexOf.call(all,elements[i])!==-1){
    temp.push(elements[i]);
    }
  }
  return temp;
}

var nodelist = document.querySelectorAll('div');

console.log(querySelectorFrom('.type1',nodelist));

/* 
<div class="type1">1</div>
<div class="type1">1</div>
*/
<div>
  <div class="type1">1</div>
  <div class="type1">1</div>
  <div class="type2">2</div>
</div>

3 个答案:

答案 0 :(得分:0)

function querySelectorFrom(selector, elements){
  var all = document.querySelectorAll(selector);
  var temp = [];
  all.forEach(item => {
    console.log("item", item);
    if(temp.indexOf(item) === -1){
      temp.push(item);
    }
  });
   
  console.log("all", all);

}

var nodelist = document.querySelectorAll('div');

console.log(querySelectorFrom('.type1',nodelist));
<div>
  <div class="type1">1</div>
  <div class="type1">1</div>
  <div class="type2">2</div>
</div>

答案 1 :(得分:0)

您可以使用forEach直接在现代浏览器中迭代NodeLists。但是,将两者转换为数组然后只使用正确的数组方法.filter可能会更好,它会根据测试将其元素过滤到另一个数组中:

const querySelectorFrom = (selector, elements) => {
  const elementsArr = [...elements];
  return [...document.querySelectorAll(selector)]
    .filter(elm => elementsArr.includes(elm));
};
const nodelist = document.querySelectorAll('div');
console.log(querySelectorFrom('.type1',nodelist));
<div>
  <div class="type1">1</div>
  <div class="type1">1</div>
  <div class="type2">2</div>
</div>

答案 2 :(得分:0)

在最近的浏览器中,您可以使用Element#matches过滤元素,而无需重新选择它们:

function querySelectorFrom(selector, elements) {
    return [].filter.call(elements, function(element) {
        return element.matches(selector);
    });
}

示例:

function querySelectorFrom(selector, elements) {
    return [].filter.call(elements, function(element) {
        return element.matches(selector);
    });
}

var nodelist = document.querySelectorAll('div');

console.log(querySelectorFrom('.type1', nodelist));
<div>
  <div class="type1">1</div>
  <div class="type1">1</div>
  <div class="type2">2</div>
</div>