javascript - 如何检查具有相同ID的div的内容,并为包含特定文本的div添加一个类?

标签 javascript jquery html css

例如对于下面的内容,我将如何添加类 .out-of-stock 并从第一个和第三个 div 中删除文本“nostock”:

<div id="variant">Blue nostock</div>
<div id="variant">Red</div>
<div id="variant">Yellow nostock</div>
<div id="variant">Green</div>

我试过,下面添加类,但是没有用:

$('#variant:contains("nostock")').addClass('out-of-stock');

谢谢

最佳答案

使用类而不是 id 因为 id 必须对于每个元素都是唯一的。从: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id

The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element ...

JS Fiddle

$('.variant').each(function() {
  var theHTML = $(this).html();
  
  // if it contains nostock
  if (theHTML.indexOf('nostock') > -1) {
    $(this).addClass('out-of-stock');
  }
});
.out-of-stock{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="variant">Blue nostock</div>
<div class="variant">Red</div>
<div class="variant">Yellow nostock</div>
<div class="variant">Green</div>

关于javascript - 如何检查具有相同ID的div的内容,并为包含特定文本的div添加一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34698127/

相关文章:

javascript - 使用类名访问 href 属性

Jquery 函数不适用于 AJAX 添加的 DOM 元素

html - 防止我的固定页脚重叠内容

javascript - 使用 jQuery 在文本变量中查找 div

javascript - 用表格替换 html 中逗号分隔的行

javascript - 我得到 x is not a function in javascript

javascript - 用 x% 宽的颜色填充表格单元格

javascript - bgSlider.js 需要激活幻灯片

javascript - 在 jQuery Mobile 中打开弹出窗口时如何避免上下滚动

javascript - 自动运行 Javascript 函数