19

I have a string:

var s = '<h1>heading</h1><p>para</p>';

and I want to remove the h1 element from it. Ive tried:

$(s).remove('h1');

but s still contains the h1 element Ive also tried:

s = $(s).remove('h1');

and

$('h1', s).remove();

and

$('h1', $(s)).remove();

etc etc etc

Any ideas?

Petah
  • 45,477
  • 28
  • 157
  • 213

1 Answers1

36

Update: I see you just changed the question. Now the solution would be this:

var s = '<h1>heading</h1><p>para</p>';

var $s = $(s).not('h1');

$('body').append($s);​

Try it out: http://jsfiddle.net/q9crX/19/

Because you now have more than one "top level" element in the jQuery object, you can use .not() (which is basically the opposite of .filter()) to remove the h1.

It would be the same as doing $(s).filter(':not(h1)');


Original answer

$(s).find('h1').remove();

So if you were to append the result to the body, you could do:

var s = '<div><h1>heading</h1><p>para</p></div>';

var $s = $(s).find('h1').remove().end();

$('body').append($s);​

Try it out: http://jsfiddle.net/q9crX/

user113716
  • 318,772
  • 63
  • 451
  • 440
  • 1
    @alex - That is because you need to store the jQuery object you create in a variable. When you wrap it with `$(s)` and do `.find('h1').remove()`, you're not modifying the original string. – user113716 Jul 25 '10 at 23:40
  • @patrick Ah yeah, whoops, I guess that was a big oversight on my behalf! Anyway, have a +1 :) – alex Jul 25 '10 at 23:41
  • 1
    Thanks @alex. :o) I was actually stuck at first on why it was appending the `

    ` that I had just removed, but then remembered that I needed to use `.end()` to get back to the `
    `.

    – user113716 Jul 25 '10 at 23:47
  • Hi, sorry I made a mistake in my question (now updated). It turns out the the string is not wrapper in a div. – Petah Jul 25 '10 at 23:56
  • What if element you want to remove is inside another element? Let's say I want to remove element from
    , so there remains only
    . – FrenkyB Jul 12 '17 at 19:47