Replace img with div jQuery
-
13-03-2021 - |
Question
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();
});
OTHER TIPS
An alternative could be to use this but it will erase other parent's child (as @Vide Simas said):
$(".myImage").parent().html('<div>hello</div>');
What you wrote looks like good, i've written a jsfiddle using replaceWidth
: http://jsfiddle.net/ydZg5/
The error must be somewhere else
The code below will replace an image with class name "myImageClassName" with a div containing the text "This is my div text":
$('img.myImageClassName').replaceWith('<div>This is my div text</div>');
but yeah, I gotta agree with the others.. your code looks fine.