Search code examples
javascriptinputreplace

Replace instead of append based on user input?


This function currently works for appending an img in a div. But I need a replace method instead of multiple img divs stacking on top of each other.

I'm open to solutions in jQuery as well.

function getImg(){

    var url=document.getElementById('txt').value;
    var div=document.createElement('div');
    var img=document.createElement('img');

    img.className="img-responsive";

    img.src=url;

    div.appendChild(img);

    document.getElementById('gif-btn').innerHTML=""; <!-- Correct answer -->
    document.getElementById('gif-btn').appendChild(div);

    return false;
}

Thanks in advance for any and all help. Much appreciated!


Solution

  • Before you append, you can clear out the div, then append the new one

    function getImg(){
    
        var url=document.getElementById('txt').value;
        var div=document.createElement('div');
        var img=document.createElement('img');
    
        img.className="img-responsive";
    
        img.src=url;
    
        div.appendChild(img);
    
        document.getElementById('gif-btn').innerHTML = ""; // <-- Clears the gif-btn div
        document.getElementById('gif-btn').appendChild(div);
    
        return false;
    }