简体   繁体   中英

Javascript - Replace appendChild element

JS Code

watermark([scope.videoSnapshotPath, scope.watermarkLogoPath])
    .image(myPositionFunction(scope.watermarkPosition))
    .then(function (img) {
    document.getElementById(scope.watermarkPosition).appendChild(img);
})

When user select first image, below is the result

Output

<div data-water-mark="" id="lowerRight" class="col-lg-9 col-md-6 col-sm-6 col-xs-12 padding-l-0">    
    <img src="data:image1/png;base64"> //first image
</div>

When selects any other image, the first image is not replaced with second image but gets appended.

<div data-water-mark="" id="lowerRight" class="col-lg-9 col-md-6 col-sm-6 col-xs-12 padding-l-0">    
        <img src="data:image1/png;base64"> //first image
        <img src="data:image2/png;base64"> //second image
</div>

How do I append images inside div and replace the previous image with new image selected ie replace first with second ?

PS img src is dynamically generated from a plugin js and solution is expected without jquery usage.

您可以更改src而不是附加一个新的。

$("#my_image").attr("src","data:image/png;base64");

You can use replaceChild ( documentation ).

parentNode.replaceChild(newChild, oldChild);

 var div = document.querySelector("div"); var newImg = document.createElement("img"); newImg.src = "http://placehold.it/400x150"; var swap = function(img) { div.replaceChild(img, div.children[0]); } document.querySelector("button").addEventListener("click", swap.bind(null, newImg)); 
 <div> <img src="http://placehold.it/200x150"> </div> <button>replace</button> 

In your code:

function (img) {
  var parent =  document.getElementById(scope.watermarkPosition);
  parent.replaceChild(img, parent.children[0])'
}

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