![](/img/trans.png)
[英]How to check if an html element contains it's own text (contains textNode)
[英]How to check if a HTML element contains an other one?
我想检查我的标题<h3>
是否具有highlight
的类,因此我创建了如何检查元素是否包含特定的类属性,但是我不确定如何使其适合我的用例,因为它不是包含以下内容的<h3>
该类,但其中的跨度:
我尝试执行以下代码:
$('.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.
$('h3').filter(function(){
return $(this).find('span.highlight').length != 0;
}) // do something with it
一种粗略的方法来知道您是否不知道有子选择器
$('#nameMachine *').hasClass('yourClass'); // either true or false
Try using `has` selector as given below code :
$('.liContainer div h3:has(span.highlight)').each(function(){
// code here
});
由于您使用的是jquery,这个简单的解决方案如何:
$('.liContainer div h3 .highlight').removeClass('highlight');
您可以尝试以下方法:
if( $("h3", "#nameMachine").has(".highlight") ) {
// do something
}
或更具体的版本:
if( $("> h3", "#nameMachine").has("span.highlight") ) {
// do something
}
$('span.highlight','.liContainer div h3').removeClass('highlight')
请注意,第二个CSS选择器将确定搜索第一个CSS选择器的范围。
find()
将在所有child元素中搜索。 因此,如果有想要的类,则其长度将为1, else length is 0
。
$('.liContainer div h3').each(function(i, obj) {
var hasClass = $(obj).find(".highlight");
if (hasClass.length) {
hasClass[0].classList.remove("highlight");
}
});
这样就可以了。 hasClass文档在这里
$("#nameMachine h3").hasClass("highlight")
if ($('#parent').find('#child').length) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.