如何判断具有特定类的元素是否不存在(纯JS)

huangapple go评论58阅读模式
英文:

How to tell if element with certain class does not exist (PURE JS)

问题

我有一些代码,它在一个 div 中创建了一个新的段落元素,并给它添加了类名 "taskparagraph"。我想检查是否存在具有这个类名的任何元素,如果没有,就添加另一个(无关的)段落。

我真的不知道如何做类似的事情,尽管这似乎是一个如此简单的任务。也许我只是没有搜索到正确的东西...

附言:目前我不打算使用像 jQuery 这样的 JS 库。如果使用类似这样的东西是完成此任务的唯一可能方式,请告诉我。

英文:

I have some code that creates a new paragraph element within a div and gives it the class "taskparagraph". I want to check if any elements with this class exist, and if not, add another (unrelated) paragraph.

I genuinely have no clue how to do something like this even though it seems like such a simple task. Maybe I'm just not Googling the right things...

P.S. I do not plan on using any JS libraries like jQuery for now. If using something like that is the only possible way to do this task please let me know.

答案1

得分: 1

你可以使用document.querySelector

if (!document.querySelector('.taskparagraph')) { // or compare with null
    // 没有具有类名 "taskparagraph" 的元素存在
}
英文:

You can use document.querySelector:

if (!document.querySelector('.taskparagraph')) { // or compare with null
    // no element with class "taskparagraph" exists
}

huangapple
  • 本文由 发表于 2023年2月19日 10:05:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497567.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定