Z.better
Z.better

Reputation: 398

javascript remove(selector) not working

checkout this:- jsfiddle

$('body').remove('p')

my problem is, when pass selector to remove() function the remove() seems not working,but when I use

$('body p').remove()

it works fine. so, what's the problem, please help

Upvotes: 1

Views: 68

Answers (4)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Actually <p> is a children to <body> so use children():-

$('body').children('p').remove()

$('body').children('p').remove();

// you can use find() also:- $('body').find('p').remove();
body {
  outline: 1px solid purple;
}

svg {
  outline: 1px solid purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p>
hi,there
</p>
</body>

The same thing is happening in $('body p').remove().

Why $('body').remove('p') is not working:-

AS @Jonathan Lonowski explained correctly:-

.remove(selector) is equivalent to using .filter(selector).remove(). Filtering a collection with the <body> to only <p> elements results in an empty collection, so .remove() has no effect.

Upvotes: 3

RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6006

you can use like this to remove all the 'p' tags recursivly from body

$('body').find('p').remove()

Upvotes: 0

Cyril Beeckman
Cyril Beeckman

Reputation: 1278

You can try to find your p elements in your body

$('body').find('p').remove();

Upvotes: 0

Woodrow
Woodrow

Reputation: 2832

$('body').children('p').remove()

Upvotes: 1

Related Questions