如何将<img/>元素插入<a> element

时间:2016-09-09 21:04:51

标签: javascript jquery image

I'm trying to insert an image inside of a hyperlink tag.

Current markup:

<div class="Example">
  <a href="http://www.Example.com">
    <img src="http://www.Example.com/Sloth.jpg">
  </a>
</div>

I want to insert

<img class="example" src="http://www.Example.com/JellyFish.jpg">

So the markup is as follows:

<div class="Example">
  <a href="http://www.Example.com">
    <img src="http://www.Example.com/Sloth.jpg">
    <img class="example" src="http://www.Example.com/JellyFish.jpg">
  </a>
</div>

Question

How can I do this via Javascript or JQuery?

4 个答案:

答案 0 :(得分:0)

使用JQuery append() ...

$("a").append('<img class="example" src="http://www.Example.com/JellyFish.jpg">');

答案 1 :(得分:0)

您可以使用insertAfter

$('<img class="example" src="http://www.Example.com/JellyFish.jpg">').insertAfter('.Example img');

希望这有帮助。

&#13;
&#13;
$('<img class="example" src="http://www.Example.com/JellyFish.jpg">').insertAfter('.Example img');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Example">
  <a href="http://www.Example.com">
    <img src="http://www.Example.com/Sloth.jpg">
  </a>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用.append()将元素插入brew info chromedriver。请注意,我已使用包含<a>作为选择器的一部分来确保特异性。

&#13;
&#13;
.Example
&#13;
$(document).ready(function(){
  $('.Example a').append('<img class="example" src="http://www.Example.com/JellyFish.jpg">')
    })
&#13;
&#13;
&#13;

答案 3 :(得分:0)

要附加图像,解决方案可能是:

$('.Example a').append($('<img>', {class: 'example', src: 'http://www.Example.com/JellyFish.jpg'}));

摘录:

&#13;
&#13;
$(function () {
  $('.Example a').append($('<img>',
                           {class: 'example', src: 'http://www.Example.com/JellyFish.jpg'}));

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="Example">
    <a href="http://www.Example.com">
        <img src="http://www.Example.com/Sloth.jpg">
    </a>
</div>
&#13;
&#13;
&#13;