guub guub - 4 months ago 9
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?

Answer

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).
$myhtml.find("a").addClass("testing");
// Add a class to the root of $myhtml (i.e. the `div`) if needed.
$myhtml.addClass("div-class");
// Append the whole jquery object.
$("body").append($myhtml);
.testing {
  background-color: yellow;
}
.div-class {
  color: green;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>