jcubic
jcubic

Reputation: 66488

How to get jquery object for replaced DOM element

I want to write a plugin that call replaceWith on this, how can I select that new content so I can chain my plugin for new content.

$.fn.spam = function() {
    this.replaceWith('<span>spam</span>');
};

and I want to do something like

$('div').span().css('background-color', 'red');

replaceWith return old content, how can I get the new content?

Upvotes: 0

Views: 62

Answers (3)

jcubic
jcubic

Reputation: 66488

I found a way to do this in one line using replaceAll jquery method

$.fn.spam = function() {
    return $('<span>spam</span>').replaceAll(this);
};

Upvotes: 0

adeneo
adeneo

Reputation: 318182

$.fn.spam = function() {
    var elems = $();
    this.each(function() {
        var span = $('<span />', {text: 'spam'});
        $(this).replaceWith(span);
        elems.push(span.get(0));
    });
    return $(elems);
};

$('div').spam().css('background-color', 'red');

FIDDLE

Upvotes: 2

CtrlX
CtrlX

Reputation: 7015

maybe like this :

$.fn.span = function() {
var theNewElt = $('<span>spam</span>');
this.replaceWith(theNewElt);
return theNewElt;
};


$('div').span().css('background-color', 'red');

Test it on jsfiddle

Upvotes: 1

Related Questions