Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access document's title element with jQuery (IE 8)

I'm seeing this issue in Internet Explorer 8, but not in Safari or Firefox. So far, I have not tested in other IE versions.

I am developing my own jQuery plugin and, for this question, I've stripped it down to the two relevant lines.


In IE 8, using the code below, $('title').text() does not do anything. docTitle is blank because title is blank, as if the jQuery selector for <title>, $('title') is not working. (Again, AFAIK, this is just in IE 8)

(function ($) {
    $.fn.myPlugin = function (options) {

        var title = $('title').text(),
            docTitle = escape(title);

    };
})(jQuery);

http://jsfiddle.net/sparky672/YMBQ2/


However, using the plain JavaScript code below, document.title is working fine in everything including IE 8...

(function ($) {
    $.fn.myPlugin = function (options) {

        var docTitle = escape(document.title);

    };
})(jQuery);

EDIT:

It does not matter that this code is inside a plugin.

Same result in IE 8 with this...

$(document).ready(function () {    
    var title = $('title').text();
    alert(title);
});

Just to clarify, I am not insisting on using this. In fact, I fixed my plugin by simply using document.title instead. If it wasn't clear initially, I'm just asking why this does not work in IE 8.


Can anyone explain why, or what stupid mistake I may have made here?


EDIT 2:

Here are some jQuery Bug reports on this issue

http://bugs.jquery.com/ticket/7025

http://bugs.jquery.com/ticket/5881

http://bugs.jquery.com/ticket/2755

And dozens of others reporting the same thing. The official response is to state, "document.title is the only reliable cross-browser way and should be used instead" and the Ticket is closed. So there you go.

like image 529
Sparky Avatar asked Oct 25 '11 23:10

Sparky


1 Answers

I guess jQuery iterates over all TextNodes and concatenates its nodeValue. IE stores this value differently than other browsers.

var title = document.getElementsByTagName('title')[ 0 ];
title.firstChild // This would be the Text-Object with the characterdata of the title
                 // Firefox: [object Text]
                 // IE: null

This should be the reason you cannot get the textContent with jQuery.text(). title.text seems to be cross browser comp. I only tested it in IE 7 and Firefox 3.6 but you can check the other browser if you like. But why not using document.title?

like image 140
Saxoier Avatar answered Oct 23 '22 17:10

Saxoier