11

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'

mdennisa
  • 177
  • 2
  • 13

2 Answers2

10

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.

AaronLS
  • 37,329
  • 20
  • 143
  • 202
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
3

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());
    });
});
Andrew Bullock
  • 36,616
  • 34
  • 155
  • 231
  • thx andrew, my intention is to have access to manipulate everything inside the actual 'obj', $('.size').click(function(){ var obj = $(this), repl = $('
    whats up man ??!
    '); obj.replaceWith(repl); alert(obj.find('span').attr('class')); // this will print 'undefined' // I want to get the class name from the actual 'obj' });
    – mdennisa Aug 26 '10 at 09:28
  • but you know you just assigned `size` to it, so why aren't just just alerting `size`? just do: `replacement.find('span').attr('class')` if you really must – Andrew Bullock Aug 26 '10 at 09:35
  • yes andrew, your code has solved my question in the first place. but I think I missunderstood. here is the final result http://jsfiddle.net/HCXaK/1/ – mdennisa Aug 27 '10 at 03:20