是否有与jQuery .has()等效的普通JS? [英] Is there a vanilla JS equivalent of jQuery .has()?

查看:36
本文介绍了是否有与jQuery .has()等效的普通JS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此jQuery选择器中具有:的香草JS等效项是什么?

What would be the vanilla JS equivalent of :has in this jQuery selector?

$('.main-container').children('.analytics:has(a)').not('#promo')

.main-container 内,我试图选择所有ID为"promo"且不含< a> <的 .analytics 元素/code>标记.

Within .main-container, I'm trying to select all .analytics elements without an id of "promo" that contain <a> tags.

我尝试过的事情:

document.querySelectorAll('.main-container .analytics:not(#promo)')

这将使我更接近我想要的东西,但我仍然必须过滤掉那些没有拥有< a> 标记.

This will give me close to what I want, but I still have to filter out those .analytics parents that do NOT have <a> tags.

使用香草JS处理此问题的最佳方法是什么?

What would be the best way to approach this using vanilla JS?

推荐答案

  1. 查询文档以使用所需的选择器,在这种情况下: .analytics:not(#promo)
  2. 将NodeList转换为数组
  3. 使用谓词过滤数组: element =>element.querySelector('您的选择器')

如果未找到子元素,则

element.querySelector('your-selector')的计算结果为 null (为false)

element.querySelector('your-selector') will evaluate to null (which is falsey) if no child element is found

通常作为功能

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.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>

这篇关于是否有与jQuery .has()等效的普通JS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆