查找并替换子元素的style属性

Find and replace style attribute from the child element

本文关键字:style 属性 元素 替换 查找      更新时间:2023-09-26

我想遍历子元素并删除/修改一些样式属性。我的div是动态生成的,我可以访问它的id。div可以是

<div id="headline" style="position">
    <div style="text-align: center;">
        <b style="color: rgb(255, 204, 153);"><font size="5">Expansion Pack</font></b>
    </div>
</div>

<div id="headline" style="position">
    <div style="text-align: center;"> 
        <span style="color: rgb(255, 204, 153);">
            <font size="4">Expansion Pack</font>
        </span>
    </div>
</div>

我想改变标题子元素的字体大小和颜色。

我知道如何读取父div

中的所有元素
$('#headline').find('*').each(function() {
     // do stuff
});

但是我怎么能找到样式属性的颜色和改变颜色或找到字体大小和改变字体的大小呢

您可以尝试下面的DEMO

$('#headline').find('*').each(function (i, item) {
    var color = $(item).find("b,span");
    var font = $(item).find("font");
    $(color).css('color', 'red');
    $(font).css('font-size', '50px')
});

这是你要找的吗?

#headline font {
    font-size:23px;
}

JSFiddle

如果我做对了,这就是你需要做的:

$('#headline').each(function() {
     $(this).find('div').css({
       'font-color': 'blue',
       'font-family': 'arial',
       ...
     });
     $(this).find('font').css({
       'font-color': 'red',
       'font-family': 'roboto',
       ...
     });
}); 

或者您可以使用:

获取样式值
var font-size = $(this).find('div').css('font-size');