JavaScript: Setting page title tag issues with HTML encoding

There is a mobile optimized version of this page, view AMP Version.

This one has been causing me to rip my hair out, literally!
So here is the scenario… You have an element in your DOM that contains some text, you wish to fetch that text and set it as the page title dynamically.

So thinking this is the easy part of your JavaScript for today, you quickly build together the below JavaScript:

$(document).attr('title', ($("#elementID").html()));

Bobs your uncle – everything is working great, you move on to more important and more complex things required for your project. But then you notice the page title isn’t quite right! You can see that special characters are HTML encoded using ampersand so you see this:

This & that

Instead of what you expected to see:

This & that

You do that “another quirk in JavaScript” sigh, sit and scratch your head, wondering exactly HOW your going to get around this.

Well if this is the problem you’re facing then look no further as I have found a solution!! When you set your page title, just drop it into a “memory DOM element” using jQuery, and then read it out using .text(), like so:

title = $('#elementID').html();
$(document).attr('title', ($("<div/>").html(title).text()));

Hopefully this should help a few people Smile

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips


Leave a Reply: