guub guub - 3 months ago 7
HTML Question

HTML string is not appended

I have a variable containing a string of HTML

var myhtml = "<div><a>DEMO</a></div>";

Before I append the HTML, I want to make changes to it, so I do this.

$("body").append( $(myhtml).filter("a").addClass("testing") );

However, nothing is appended, and I get no console errors. How can I alter the HTML and still append it normally?


There is two things to take into account:

  1. filter changes the jQuery object on which it is called. In your case, it will only keep a and remove the parent div. You should use find instead.find will return a new jQuery object without altering the original one.
  2. However, you cannot directly insert the result into your DOM. find returns a new jQuery object that contains only a. If you want to keep the parent div, you must insert the first jQuery object.

var myhtml = "<div><a>DEMO</a></div>";
// Parse the string into a jquery object.
var $myhtml = $(myhtml);
// Add the "testing" class to the `a` child(ren).
// Add a class to the root of $myhtml (i.e. the `div`) if needed.
// Append the whole jquery object.
.testing {
  background-color: yellow;
.div-class {
  color: green;  
<script src=""></script>