Search code examples
jqueryimagereplacewith

Replace img with div jQuery


I'm looking to replace an image with a class to a div with text inside it, how can I do that?

<script>
$('img.vCSS_img_history_off').replaceWith('<div id="button">Turn History Off</div>');
</script>

I know that code is screwed up, but it's just to paint a picture of what I'm looking for, any suggestions?


Solution

  • You need to make sure the DOM is ready before you go searching for elements in it:

    $(document).ready(function(){
        $('img.vCSS_img_history_off').replaceWith('<div id="button">Turn History Off</div>');
    });
    

    Alternatively, you can add whatever you need to after the image and then remove it:

    $(document).ready(function(){
        $("img").after("<div>Inserted div</div>").remove();
    });
    

    Example.

    More on .after() here and more on .remove() here.