最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I put logical operators in document.querySelectorAll? If so, how? - Stack Overflow

programmeradmin9浏览0评论

Let's say I want to find all div elements and span inside p.

Is it possible to get all what I want in a single querySelectorAll invocation?

Conceptually it should be something like document.querySelectorAll("div | p span") (where | means or).

Let's say I want to find all div elements and span inside p.

Is it possible to get all what I want in a single querySelectorAll invocation?

Conceptually it should be something like document.querySelectorAll("div | p span") (where | means or).

Share Improve this question edited Mar 4, 2022 at 10:18 victor.ja 8882 gold badges11 silver badges30 bronze badges asked Apr 11, 2016 at 9:35 Just a learnerJust a learner 28.5k53 gold badges164 silver badges246 bronze badges 4
  • 2 Can you put logical operators on CSS selectors? – Ismael Miguel Commented Apr 11, 2016 at 9:35
  • document.querySelectorAll("p div, p span") – Rajaprabhu Aravindasamy Commented Apr 11, 2016 at 9:36
  • @RayonDabre That is wrong. That will select span elements inside p and all div elements throughout the DOM. – Rajaprabhu Aravindasamy Commented Apr 11, 2016 at 9:37
  • @RajaprabhuAravindasamy, Agreed! – Rayon Commented Apr 11, 2016 at 9:37
Add a comment  | 

1 Answer 1

Reset to default 49

Yes. You can use the same logical operators allowed in CSS:

OR: chain selectors with commas

document.querySelectorAll('div, p span');
// selects divs, and spans in ps

AND: chain selectors without whitespace

document.querySelectorAll('div.myClass');
// selects divs with the class "myClass"

NOT: :not()-selector

document.querySelectorAll('div:not(.myClass)');
// selects divs that do not have the class "myClass"
发布评论

评论列表(0)

  1. 暂无评论