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

StackOverflow https://stackoverflow.com/questions/3573521

  •  01-10-2019
  •  | 
  •  

문제

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'

도움이 되었습니까?

해결책

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.

다른 팁

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());
    });
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top