Mike Mengell
Mike Mengell

Reputation: 2398

jQuery selector editing HTML before adding to the DOM

I am trying to add some content to the DOM using a jQuery selector but I want to manipulate it before it gets added.

var $content = $('<h1>title</h1><h2 id="xx">remove me</h2><p>some content or other</p>');

$content.remove('#xx');

$('#output').append($content);

I have put this on jsfiddle here http://jsfiddle.net/NNcG5/1/

Many thanks, Mike

Upvotes: 3

Views: 159

Answers (3)

Pointy
Pointy

Reputation: 413818

I think the problem stems from the fact that you're creating a fragment that does not have a single top-level element. If you wrap that all in a <div> then it works fine.

var $content = $('<div><h1>title</h1><h2 id="xx">remove me</h2><p>some content or other</p></div>');

edit — oops also I changed your removal code exactly as Mr. Dimitrov did in his answer.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039050

Try like this:

var $content = $('<div/>').html($('<h1>title</h1><h2 id="xx">remove me</h2><p>some content or other</p>'));
$content.find('#xx').remove();
$('#output').append($content);

Live demo.

Upvotes: 3

Martin
Martin

Reputation: 6687

I'd recommend $content.not('#xx').appendTo('#output');

I also updated your JS Fiddle with the solution too, here.

Upvotes: 5

Related Questions