Understanding .remove() better


#1


https://www.codecademy.com/courses/web-beginner-en-v6phg/0/5?curriculum_id=50a3fad8c7a770b5fd0007a1

Hi all. Variations on the correct solution to jQuery exercise 3.5 (the 'remove' function) have already been posted. But I've been struggling with variations that work (they remove the paragraph text) but don't pass the codecadamy check.

Can anyone explain the difference between the three variations on .remove posted below, and why codecademy only accepts the first one?


//this works and passes
$(document).ready(function() {
    var $p = $('<p>To add</p>');
    $('#one').after($p);
    $('#two').after($p);
    $('p').remove();
    });

//this works, doesn't pass
$(document).ready(function() {
    var $p = $('<p>To add</p>');
    $('#one').after($p);
    $('#two').after($p);
    $($p).remove();
    });

//this works, doesn't pass
$(document).ready(function() {
    var $p = $('<p>To add</p>');
    $('#one').after($p);
    $('#two').after($p);
    $p.remove();
    });


#2

Kiss every paragraph element goodbye, and pray they are not used in page layout structure.


#3

Thanks mtf. That's what I actually guessed would happen. In that case, why is that the 'best' code that gets the pass?

I first tried the second one;

$($p).remove();

thinking that just removes the variable $p. And it seems to do that. But the code doesn't pass the codecademy check. Is there a reason it is preferred we go for $('p').remove();

As for the third code block, where I have;

$p.remove();

I've no idea how this is different except that we are not assigning a new jQuery object. So I feel like the third 'should' be the best solution in terms of economy of style, but I don't know. Could someone tell me if I'm right?


#4

We do not make new selectors from jQuery objects. That's a circular reference. They are already jQuery objects.