Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery, remove element from string

Tags:

jquery

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?

like image 419
Petah Avatar asked Jul 25 '10 23:07

Petah


People also ask

How remove and append in jQuery?

jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.


1 Answers

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)');

  • http://api.jquery.com/not/
  • http://api.jquery.com/filter/

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/

like image 143
user113716 Avatar answered Oct 02 '22 12:10

user113716