gpt4 book ai didi

javascript - 如何检查一个 HTML 元素是否包含另一个元素?

转载 作者:行者123 更新时间:2023-11-28 04:16:59 26 4
gpt4 key购买 nike

我想检查我的标题是否<h3>有课highlight所以我创立了How to check if element contains specific class attribute但我不确定如何使其适合我的用例,因为它不是 <h3>其中包含类,但包含其中的跨度: enter image description here

我尝试执行此代码:

$('.liContainer div h3').each(function(i, obj) {
var contains = false;
String classes = obj.getAttribute("class");
for (String c : classes.split(" ")) {
if (c.equals("highlight")) {
contains = true;
}
}
if(contains){
obj.classList.remove("highlight");
}
});

但我在实际代码中遇到错误:

imports/ui/layout.js:42:13: Unexpected token (42:13)

这是行 String classes = obj.getAttribute("class");

有人可以帮我让它工作吗?[编辑] 在您的回答的帮助下,我现在在这里:

'click .liContainer div h3': function(e){
if ( $(e.target).find("span").is(".highlight") ) {
console.log("it was highlighted");
$(e.target).find("span").removeClass('highlight');
}
},

成功了,谢谢大家

最佳答案

    I hope it will help you

$('.liContainer div h3').each(function(i, obj) {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});

**can you just help me to do the action only on the clicked h3?**

If `click` action:

$('.liContainer div h3').click(function() {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});

I use your code, and change the content of the `each` loop.
You loop each `<h3>` and check if child `<span>` has class `.highlight`, then you do something...

The above Code can also be written as follows:

$('.liContainer div h3').click(function() {
if ( $(this).find("span.highlight") ) {
// do something
}
});
Hope this works fine.

关于javascript - 如何检查一个 HTML 元素是否包含另一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42781421/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com