In the source code of a WordPress plugin called Advanced Ajax Page Loader, I see the author using code like this to set the page title after ajax succeedes:
data = data.split('<title>')[1];
titles = data.split('</title>')[0];
jQuery(document).attr('title', (jQuery("<div/>").html(titles).text()));
I tried to replace the last line with
jQuery(document).attr('title', titles);
and the plugin also worked.
So my question is: why he uses (jQuery("<div/>").html(titles).text())
instead of simply applying titles
the variable?
And what does (jQuery("<div/>")
exactly mean?
Thanks.
That is syntax to create a new div
element.
jQuery("<div/>")
creates a div element, see http://api.jquery.com/jquery/#jQuery2. Here it's used to sanitize the titles
var.
jQuery("<div/>").html(titles).text()
creates an empty div (jQuery("<div/>")
), sets the content to titles
(.html(titles)
) and reads the text of this div (.text()
). HTML tags get read as text, so no HTML/JS can be injected into the document title, only pure text. It's a security feature of this script.