我有很多内容,例如
<div id="justThisDIV"><p>Some paragraph <img src="http://mydomain.com/image.jpg"/> </p>
<p><img src="http://mydomain.com/wow.png"/></p>
<p><img src="http://notmydomain.com/blah.png"/> Wow this is boring</p></div>
如何将类添加到我的域中的所有图像,即将ID为dyd的URL包含在ID为justThisDIV
的DIV中我试过以下但没有去
<script type="text/javascript">
$(document).ready(function() {
$("div#justThisDIV img[src*=mydomain.com]").addClass("full-width");
});
</script>
由于
答案 0 :(得分:3)
ANSWER再次编辑
您需要添加 'attribute contains' selector ,然后将.parent().attr('id')
与条件表达式一起使用,将其添加到您想要添加到的div中。
$("img[src*='imgur']").each(function () {
if($(this).parent().attr('id') == "thisDiv") { $(this).addClass('mine')}
});
或者,如果要将类添加到容器中,只需更改引用:
$("img[src*='imgur']").each(function () {
if($(this).parent().attr('id') == "thisDiv") { $(this).parent().addClass('mine')}
});
答案 1 :(得分:1)
以下正是您所需要的
$('img')
.filter(function() {
return this.src.match(/^http:\/\/mydomain.com/);
})
.addClass("full-width");
jsfiddle链接:http://jsfiddle.net/4YXDS/
答案 2 :(得分:0)
您可以尝试使用以。开头的属性 示例:强>
$( "img[src^='mydomain.com']" ).addClass('myClassName');
答案 3 :(得分:0)
不要在可能不存在的DOM元素上触发函数。检查它们是否存在,然后采取行动。
var $img = $('img[src*="mydomain.com"]');
// Check if at least one image you need exists
if ($img.length) {
$img.each(function() {
// Add custom class to each img tag
$(this).addClass('my_class');
});
}
确实只能输入以下内容来添加类:
$('img[src*="mydomain.com"]').addClass('my_class');
但是,我觉得这样做很好: