是否有一个类似于jQuery .has()的vanilla JS?

时间:2018-03-20 20:11:46

标签: javascript jquery

在这个jQuery选择器中有什么香草JS相当于?

final KStream<String, String> inputStream = builder.stream("inputStream");
...
inputStream
    .filter(this::acceptCertainMessages)
    .transform(new MyTransformerSupplier<String, String>("store"), "store")
    .to("outputStream");

$('.main-container').children('.analytics:has(a)').not('#promo') 内,我正在尝试选择所有.main-container个元素,而不包含包含.analytics标记的“promo”ID。

我尝试了什么:

<a>

这会让我接近我想要的内容,但我仍然需要过滤掉拥有document.querySelectorAll('.main-container .analytics:not(#promo)') 代码的.analytics个父母。

使用vanilla JS解决这个问题的最佳方式是什么?

3 个答案:

答案 0 :(得分:4)

  1. 查询文档以使用所需的选择器,在本例中为.analytics:not(#promo)
  2. 将NodeList转换为数组
  3. 使用谓词element => element.querySelector('your-selector')
  4. 过滤数组
      如果没有找到子元素,

    element.querySelector('your-selector')将评估为null(这是假的)

    一般作为一种功能

    function has(nodeList, selector) {
      return Array.from(nodeList).filter(e => e.querySelector(selector))
    }
    
    const nodeList = document.querySelectorAll('.main-container > .analytics:not(#promo)')
    
    has(nodeList, 'a').forEach(e => e.style.background = "red")
    <div class="main-container">
      <div class="analytics">
        <a>Should be red</a>
      </div>
      <div class="analytics">
        Should not be red
      </div>
      <div id="promo" class="analytics">
        <a>Should not be red</a>
      </div>
    </div>

    作为NodeList.prototype

    NodeList.prototype.has = function(selector) {
      return Array.from(this).filter(e => e.querySelector(selector))
    }
    
    document
      .querySelectorAll('.main-container > .analytics:not(#promo)')
      .has('a')
      .forEach(e => e.style.background = 'red')
    <div class="main-container">
      <div class="analytics">
        <a>Should be red</a>
      </div>
      <div class="analytics">
        Should not be red
      </div>
      <div id="promo" class="analytics">
        <a>Should not be red</a>
      </div>
    </div>

答案 1 :(得分:1)

您可以选择<a>,然后获取其父节点:

var a = document.querySelectorAll('.main-container .analytics:not(#promo) a');
var yourElements = [];
for (var i = 0; i < a.length; i++) {
  yourElements.push(a[i].parentNode);
}

yourElements.forEach(e => e.style.background = "red");
<div class="main-container">
  <div class="analytics">
    <a>Should be red</a>
  </div>
  <div class="analytics">
    Should not be red
  </div>
  <div id="promo" class="analytics">
    <a>Schould not be red</a>
  </div>
</div>

编辑:只是注意到这只有在<a>是您想要的元素的直接子项时才有效。

答案 2 :(得分:1)

:has没有等效的选择器,你必须使用初始选择,然后过滤它们

var el = document.querySelectorAll('.main-container > .analytics:not(#promo)');
var res = [];
for (let x = 0; x < el.length; x++){
    if (el[x].querySelector('a')) res.push(el[x]);
}
//res has has the array of elements needed.