如果JQuery中有属性,则将类添加到元素

时间:2015-12-11 12:08:19

标签: jquery html

如果某个类具有包含变量数据的'style'属性,如何将它添加到div元素?

    <div style="background-color: #000;">
    </div>

我想要实现的是一个脚本,它会自动为具有上述属性的每个div元素添加一个类post-with-bg

4 个答案:

答案 0 :(得分:2)

试试这个:

$(document).ready(function(){
    $('div[style*="background-color: #000"]').addClass('post-with-bg');
});

答案 1 :(得分:1)

您可以使用.filter()

$("div").filter(function () {
  return $(this).attr("style") != "";
}).addClass("post-with-bg");

但是这会在字面上添加所有<div>的类。因此,最好以这种方式选择父级:

$(".affect-these div").filter(function () {
  return $(this).attr("style") != "";
}).addClass("post-with-bg");

答案 2 :(得分:1)

这将获取HTML中的所有div并检查颜色是否为#000。如果是,则添加类post-with-bg

$('div').each(function() {
    if($(this).css('background-color') == "rgb(0, 0, 0)")
      $(this).addClass("post-with-bg");
});

答案 3 :(得分:1)

您只需使用以下selectordiv[style="background-color: #000;"]

即可
$('div[style="background-color: #000;"]').addClass('post-with-bg');

更新: 如果您想通过style属性定位所有具有背景设置的div,而不仅仅是黑色背景,请改用以下内容:

$('div[style*="background-color"').addClass('post-with-bg');
相关问题