Change img to div with background, with jQuery

I would like to use jQuery to switch all img elements with a specific class to a div with a background. So that's it:

<img class="specific" src="/inc/img/someimage.png" />

becomes:

<div class="specificDiv" style="background: url(/inc/img/someimage.png); width: fromImageElementPX; height: fromImageElementPX;"></div>

I would like to do this to get around corners using css3. The CMS user, the client, can only insert IMG elements.

Thanks in advance.

+3
source share
5 answers

The easiest way I can think of:

$('.specific').replaceWith(function () {
    var me = $(this);
    return '<div class="specificDiv" style="background: url(' + me.attr('src') + '); width: ' + me.width() + 'px; height: ' + me.height() + 'px;"></div>';
});
+4
source
$('img.specific').each(function(){ //iterate through images with "specific" class
    var $this = $(this), //save current to var
        width = $this.width(), //get the width and height
        height = $this.height(),
        img = $this.attr('src'), //get image source
        $div = $('<div class="specificDiv"></div>')
        .css({
            background: 'url('+img+')', //set some properties
            height: height+'px',
            width: width+'px'
        });
    $this.replaceWith($div); //out with the old, in with the new
})
+2
source

, .

var origImage = $(".specific");
var newDiv = $("<div>").addClass("specificDiv");
newDiv.css("background-image", "url('" + origImage.attr("src") + "')");
newDiv.width(origImage.width()).height(origImage.height());
origImage.replaceWith(newDiv);
+1

http://jsbin.com/ozoji3/3/edit

$(function() {
  $("img.rounded").each(function() {
    var $img = $(this),
        src = $img.attr('src'),
        w = $img.width(),
        h = $img.height(),
        $wrap = $('<span class="rounded">').css({
            'background-image': 'url('+ src +')',
            'height': h+'px',
            'width': w+'px'
          });
    $(this).wrap($wrap);
  });
});
0

( Andrew Koester) - . ...

$.fn.replaceImage = function() {
  return this.each(function() {
    var origImage = $(this);
    var newDiv = $("<div>").attr("class", "specificDiv");
    newDiv.css("background", "url('" + origImage.attr("src") + "')");
    newDiv.width(origImage.width()).height(origImage.height());
    origImage.replaceWith(newDiv);  
  });
};

, , - ...

$(".specific").replaceImage();
0

Source: https://habr.com/ru/post/1779451/


All Articles