views:

91

answers:

1

Hi, I have a javascript page which I am looking at localising. I have the translation handled, however one thing I am having difficulty with is the best way to handle which text to set. Obviously, for a button I should set the title / value. For a span probably the innerHTML / innerTEXT and for an image the alt. I was wondering if there is any function in JQuery which will allow me to call a generic function which will set the alt or value or innerHTML based on the nodeType.

basically a nice way of doing this:

if(this.nodeName == "input")
{
    this.value = "newButtonText"
}
if (this.nodeName == "SPAN")
{
    this.innerHTML = "newSpanText";
}

any help would be handy.

Thanks

John

+1  A: 

Well, I don't think there is one, but you can implement it yourself.

(function ($) {
    $.fn.caption = function (newText) {
        return this.each(function () {
            var $this = $(this);
            if ($this.is(':submit')) {
                $this.val(newText);
            } else if ($this.is('img') {
                $this.attr('alt', newText);
            } else {
                // A simple dome element like span, div, etc.
                $this.text(newText);                
            }
        });
    }
})(jQuery);

Usage is as follows:

$('#coolImg').caption("New caption in English");

The (function ($) {})(jQuery) part is a standard jquery idiom when writing plugins. Check the jquery docs for plugin authoring for more information. Also, it's a good idea to use the functionality provided by jquery (in forms of methods like text() and html()) to avoid browser inconsistencies.

P.S. The solution with body * will be very slow for slightly larger documents.

Emil Ivanov