I am working on upgrading some old software that was using jQuery version 1.7.2. I have upgraded this to version 1.12.1 due to some new plugins that have been added and require a newer version of jQuery.
There is however loads of jQuery that uses the jQuery(htmlString) format, for example:
var html = $("<div>");
// Prepare the <div> of comments
$.each(data.comments, function() {
console.log(this);
html.append(
$("<div>").attr("class", "comment").html(
$("<div>").attr("class", "comment-profile-pic").html("").after(
$("<div>").attr("class", "comment-text").html(
$("<h1>").html(
this.full_name + " at " + this.started_datetime
).after(
$("<p>" + this.text + "</p>")
)
)
)
)
);
});
It looks like $(htmlString) was depreciated in version 1.9 and reading the upgrade guide at https://jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring it states the format for recognising if html is passed into the selector has changed however it also says:
When the jQuery Migrate plugin is used, it will use the old rules for determining if the string passed to $() "looks like HTML".
I have attached the jQuery migrate plugin version 1.4.1 but it doesn't seem to have made any difference and will still not recognise HTML in a selector.
EDIT: I have tried reverting jQuery to version 1.8.0 and it works as expected, but then version 1.9.0 breaks it. This means it is definitely an issue with the upgrade to v 1.9.
Also after doing further tests i have realised that passing html into a selector does work when you do something like $("<div>").attr("class", "comment")
but does not work when you nest as in the above example.
Is anyone aware of how to get around this issue without re-writing all of the code that passes HTML into a selector?
<
character:As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior. If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup
html()
. I've added an answer for you below