JS - how to remove image with JavaScript?

前端 未结 9 1408
孤独总比滥情好
孤独总比滥情好 2021-02-13 11:27

I faced a problem as to remove image with JS code like a...


...
document.getElementById(\'image_X\').src=\'\'


        
相关标签:
9条回答
  • 2021-02-13 12:07

    Gets its parent and use removeChild.

    var parent = getElementById('parentid');
    var child = document.getElementById('imagex');
    parent.removeChild(child);
    
    0 讨论(0)
  • 2021-02-13 12:08

    You could just hide it. In vanilla JS that would be:

    document.getElementById("image_X").style.display='none';
    

    In jQuery:

    $("#image_X").css('display', 'none');
    

    If you really want to remove it from DOM, there is removeChild method you could invoke on the parentNode of your image element.

    0 讨论(0)
  • 2021-02-13 12:12
    var image_x = document.getElementById('image_X');
    image_x.parentNode.removeChild(image_x);
    

    http://jsfiddle.net/5DdyL/

    0 讨论(0)
  • 2021-02-13 12:15

    This should do it:

    var el = document.getElementById('image_X');
    el.parentNode.removeChild(el);
    

    You can try it here.

    You can neatly wrap that into a function like so:

    function removeElement(ele) {
        ele.parentNode.removeChild(ele);
    }
    
    removeElement(document.getElementById("image_X"));
    
    0 讨论(0)
  • 2021-02-13 12:15

    I want to share some additional tips...

    @Marecky, Thank to Jared Farrish answer I could figure out some helpful points concerning JS...

    But next I had to make my own additional research as well... It is not a super fact, but a little theory tip... So, as a result, I could find that browsers, as a any desktop app, of course, are created with some kind of GUI framework... As a rule, most GUI (for example Swing) frameworks, of course, may using double buffered objects to display graphics... So when it (FF for example) re-translates script to graphic objects the GUI sync rules come to life...

    ...OK... Coming from GUI re-painting problems to scripting itself...

    So my question was about playing around DOM objects... The fact was the img tag doesn't update UI event if the code like document.getEelementById('image_X').src='' is activated; So the <body> tag space (for some reason) , I am not sure but, is keeping some kind of 'cached' state... And maybe that makes img (if it is in body) become 'static'; So I had to find some helpful additional object which supports dynamic UI update. As a test, I used div instead of the pure body tag to keep img in it; So not to update body but div inner content only and that helped. So using JS + HTML in my case was helpful...

    I hope the tip saves ones day

    0 讨论(0)
  • 2021-02-13 12:15

    Try

     document.getEelementById('image_X').src="''"; 
    

    but it will display a broken image

    0 讨论(0)
提交回复
热议问题