将类添加到特定div中的img标记

时间:2015-05-28 03:43:26

标签: jquery css

这是我的样本div:

<div id="question-display">
    <img src="/assets/img/sample.png" /> //Line 1
    <img src="/assets/img/sample.png" /> //Line 2
    <img src="/assets/img/sample.png" /> //Line 3
</div>

我如何使用jquery,例如:

$('img').addClass('img-responsive');

并将等级img-responsive添加到div id="question-display"

中的img标记

使用jquery后的预期输出:

<div id="question-display">
    <img class="img-responsive" src="/assets/img/sample.png" />  //Line 1
    <img class="img-responsive" src="/assets/img/sample1.png" /> //Line 2
    <img class="img-responsive" src="/assets/img/sample2.png" /> //Line 3
</div>

2 个答案:

答案 0 :(得分:3)

在id为'question-display'

的元素中添加img
$('#question-display img').addClass('img-responsive');

答案 1 :(得分:0)

通过放置空格

来选择img后代
$('#question-display img').addClass('img-responsive');

如果您希望定位直接后代,请使用>

$('#question-display > img').addClass('img-responsive');

&#13;
&#13;
$('#question-display img').addClass('img-responsive');
&#13;
.img-responsive{
  border:1px solid green;
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="question-display">
    <img src="/assets/img/sample.png" /> 
    <img src="/assets/img/sample.png" /> 
    <img src="/assets/img/sample.png" /> 
</div>
&#13;
&#13;
&#13;