DOM遍历不适用于prev()?

时间:2014-12-30 09:20:02

标签: javascript jquery dom

我的DOM看起来像这样

http://i.imgur.com/iChsIm2.png

和我的Jquery:

$('.content').each(function(){
    $(this).find('img').prev().removeAttr('height width style');
});

为什么div仍然附有风格?

3 个答案:

答案 0 :(得分:0)

您需要使用parent()closest()喜欢,

$('.content').each(function(){
     $(this).find('img').closest('div').removeAttr('height width style');
});

如果你有多张图片,那么你可以使用h3元素中的next(),例如

$('.content').each(function(){
     $(this).find('h3').next('div').removeAttr('height width style');
});

如果您只想要具有父div的图像,那么您可以尝试它,

$('.content > div').each(function(){
     $(this).find('img').closest('div').removeAttr('height width style');
});

答案 1 :(得分:0)

你可以用,

$('.content').each(function(){
     $(this).find('img').parent().closest('div').removeAttr('height width style');
});

希望这有帮助。

答案 2 :(得分:0)

如果你想使用更短的代码,那么你可以使用它:

$('.content div[style]:has(img)').removeAttr('style');

这会有效,因为div.content div的孩子,除了width, height之外没有style个属性。

Working Demo.

Non-working Demo.

非工作演示:选择器上没有属性,因此不会受到影响。

相关问题