简体   繁体   中英

Set src attribute of img tag with javascript

I have the following elements in a html document

<div id="u11" class="ax_default image" data-label="image1">
    <img id="u11_img" class="img " src="images/image1_u11.png">
</div>

<div id="u23" class="ax_default image" data-label="image2">
    <img id="u23_img" class="img " src="images/image2_u23.png">
</div>

I want to write a javascript onclick function for another element that set image2 src to image1 src

The problem is that ids are random so I cannot use them but fortunately I can use the data-label to get the external div objects with $('[data-label=image1]')

¿How can I set the src in the inner img?

You can use the following

var image1 = document.querySelector('[data-label="image1"] img'),
    image2 = document.querySelector('[data-label="image2"] img');

document.querySelector('#button').addEventListener('click', function(){
    image2.src = image1.src;
});

here is an example using each function :

 $( "#change" ).click(function() { // get all image element in body var selects = $('body').find('img'); // loop throw them selects.each(function(index, el) { if(index !== selects.length - 1) { //save the img src to local variable var img1 = selects[index].getAttribute('src'); var img2 = selects[index+1].getAttribute('src'); // change the imgs src selects[index].src = img2; selects[index+1].src = img1; // and have a nice day ^^' } }); }); 
 img{ max-width:95px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div id="u11" class="ax_default image" data-label="image1"> <img id="u11_img" class="img " src="https://media-cdn.tripadvisor.com/media/photo-s/0e/4c/55/8d/merzouga.jpg"> </div> <div id="u23" class="ax_default image" data-label="image2"> <img id="u23_img" class="img " src="http://www.classetouriste.be/wp-content/uploads/2012/11/sahara-01.jpg"> </div> <button id="change">Change images</button> 

this code will work no matter how many img you have in your body or you can just set the element that contain the image var selects $('#yourelementid').find('img');

You could change the entire code with the src included.

 function myFunction() { document.getElementById("u11").innerHTML = '<img id="u23_img" class="img " src="images/image2_u23.png">'; } } 
 <div id="u11" class="ax_default image" data-label="image1"> <img id="u11_img" class="img " src="images/image1_u11.png"> </div> <div id="u23" class="ax_default image" data-label="image2"> <img id="u23_img" class="img " src="images/image2_u23.png"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM