Javascript 元素标题包括并向其添加类
如何将类附加到包含如下特定文本的特定元素:Javascript 元素标题包括并向其添加类,javascript,jquery,Javascript,Jquery,如何将类附加到包含如下特定文本的特定元素: var title = $('.pass-item .title').text(); if(title.includes('7 days within 1')){ // Here I want to select the element which has the title text '7 days within 1' // And append a class to it } $('.title').each(function()
var title = $('.pass-item .title').text();
if(title.includes('7 days within 1')){
// Here I want to select the element which has the title text '7 days within 1'
// And append a class to it
}
$('.title').each(function(){
if(this.text() == "yabadabadoooo")
{
this.addClass("make-me-pretty");
}
})
我希望有人能帮助我:)您可以使用jQuery搜索该元素,然后使用添加类:
$(".pass-item .title:contains('7 days within 1')").addClass("the-class");
如果没有找到,那没关系,jQuery的API是基于设置的,因此不会出错。您需要首先获取所有项的数组,它们映射到该数组,并检查每个项所包含的文本。如果它具有所需的文本,您可以将其与新类一起返回,否则只需按原样返回该项即可
let titles = document.querySelectorAll('.pass-item.title')
titles = Array.prototype.slice.call(titles);
titles.map((item) => {
if (item.textContent.includes('7 days within 1')) {
item.classList.add('new-class')
return item
} else {
return item
}
});
但是,您可以检查具有特定类或属性的每个元素,并检查它们是否包含如下文本:
var title = $('.pass-item .title').text();
if(title.includes('7 days within 1')){
// Here I want to select the element which has the title text '7 days within 1'
// And append a class to it
}
$('.title').each(function(){
if(this.text() == "yabadabadoooo")
{
this.addClass("make-me-pretty");
}
})
$('.pass item.title').addClass(“yourClassName”)
@collingertitle
将是一个string@George,修复了它,谢谢我错过了它的标题只是一个类名
?例如:.title
,或者它是一个标记名
?例如,
,或者它是一个属性?示例:
仅供参考:当您不使用它生成的数组时,使用map
不是最佳做法;只需使用forEach
。还要注意的是,在现代浏览器上,来自querySelectorAll
的节点列表具有forEach
,因此不需要切片(如果需要,也可以进行多边形填充)。.pass item.title
(在问题中)和.pass item.title
(在上面的答案中)之间也有很大的区别。最后,请注意OP使用的是jQuery,这使得它成为一个单行程序。DOM元素没有addClass
方法this
在中,每个
回调都是DOM元素,而不是jQuery对象。Woops,我已经做了一段时间了。我们可以在回调中使用$(这个)不是吗?是的,但是您根本不需要循环。