Reputation:
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
Reputation: 7887
There is two things to take into account:
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.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
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