user3758078
user3758078

Reputation:

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?

Upvotes: 0

Views: 77

Answers (2)

Quentin Roy
Quentin Roy

Reputation: 7887

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 of the calls chain into your DOM. find returns a new jQuery object that only contains 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 jquery object.
$("body").append($myhtml);
.testing {
  background-color: yellow;
}
.div-class {
  padding: 5px;
  border-style: solid; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Leonid Zakharov
Leonid Zakharov

Reputation: 970

Enjoy =)

var myhtml = "<div><a>DEMO</a></div>";
$("body").append($(myhtml).find('a').addClass("testing"))

Ok, with div:

var myhtml = "<div><a>DEMO</a></div>";
var $div = $(myhtml);
$div.find('a').addClass("testing");
$("body").append($div);

Good luck!

Upvotes: 1

Related Questions