0

Let's suppose I have some element and also have some picture in folder. So what I want to do is to take exactly this div and covert it into img tag using picture that I have as a source.

David
  • 4,332
  • 13
  • 54
  • 93

6 Answers6

3
$("#yourDiv").replaceWith("<img src='yourImage.png' />");

From the jQuery docs:

The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call.

So really, instead of "converting" the div as you ask in your question, this removes the div and replaces it with a new img element. Which should work exactly as you expected, but it's difficult to say for sure without a clearer question.

Here's an example fiddle to get you started.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

Yes you can :

$(function(){


$('div').each(function(){
   //TEST url used
    $img= $('<img>').attr('src','http://blog.irrashai.com/wp-content/uploads/2009/01/test-pilot.png');
    $(this).replaceWith($img);
});

});

Check my link : http://jsfiddle.net/R2XQp/

My example targets each DIV tag... changed code the way you want it.

Marc Uberstein
  • 12,501
  • 3
  • 44
  • 72
0

You can use the .replaceAll method.

Create a new image:

var $image = $('<img/>').attr('src', 'path/to/my/image.png');
$($image).replaceAll('#selector-of-div');

However, there might be better ways if you could clarify a bit more exactly why you are replacing a div with an img and what the usecase is :-)

supakeen
  • 2,876
  • 19
  • 19
0

select the div and replace it with the img

$("#yourDIVid").replaceWith("<img/>",{src:'yourSource'});

jquery replaceWith

Rafay
  • 30,950
  • 5
  • 68
  • 101
0
//get it from somewhere
var imgSource;

$('#yourDiv').replaceWith('<img src=")
-1

My approach would be

  • Take the div's innerHTML
  • Create your image tag and append it next to the div
  • Append the innerHTML of the div to the image tag
  • remove the div from the dom

If you try it and have problems, post your code here.

JSager
  • 1,420
  • 9
  • 18