Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get actual content of an object after being replaceWith('something') in jquery

I have this code

$(document).ready(function(){
    $('.selector').click(function(){
        obj = $(this);
        obj.replaceWith('<div class="size">whats up man ??!</div>');
        alert(obj.html());
    });
});

I want to get the new content of 'obj' that has been 'replaceWith'

but,

I get the old content instead ...

how do I get the actual content of 'obj' ???

my intention is to access the new 'obj'

$('.selector').click(function(){
            var obj = $(this),
            repl = $('<div class="size">whats up man ??! <span class="medium"></span></div>');
            obj.replaceWith(repl);
            alert(obj.find('span').attr('class')); //this will print 'undefined'
});

I want to print the class name of the 'span' which is 'medium'

like image 729
mdennisa Avatar asked Aug 26 '10 08:08

mdennisa


People also ask

How do I get the HTML inside a div using jQuery?

To load external HTML into a <div>, wrap your code inside the load() function. To load a page in div in jQuery, use the load() method.

Which jQuery function adds HTML content outside a selection?

Note: The contents or elements inserted using the jQuery before() and after() methods is added outside of the selected elements.

What is replace in jQuery?

replaceWith( newContent )Returns: jQuery. Description: Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.


2 Answers

Your updated method is the correct one, just needs a tweak like this:

$('.selector').click(function(){
  var obj = $(this),
      repl = $('<div class="size">whats up man ??! <span class="medium"></span></div>');
  obj.replaceWith(repl);
  alert(repl.find('span').attr('class')); 
});

You can test it out here. The important change is the repl.find() to look in the new element instead of the old one.

like image 98
Nick Craver Avatar answered Oct 16 '22 03:10

Nick Craver


why do you want to do that? you know what you replaced it with....

$(document).ready(function(){
    $('.selector').click(function(){
        var obj = $(this);
        var replacement = $('<div class="size">whats up man ??!</div>');
        obj.replaceWith(replacement);
        alert(replacement.html());
    });
});
like image 29
Andrew Bullock Avatar answered Oct 16 '22 01:10

Andrew Bullock