Search code examples
javascriptjquerytitleobject-literal

Most efficient way to add titles to elements with javascript/jQuery


I have some French numbers up to 24 as text in paragraph elements (some occurring more than once) on a page and I want to go through them and add the relevant English translation as a title attribute. I've got a solution, but I don't think it's the most efficient, so I'm just looking for a bit of help to write something neater, if possible, and was interested in your solutions.

Thanks


Solution

  • Create a translations object where the key is the number in French and the value is the English translation.

    var translations = {
        "un" : "one",
        "deux" : "two",
        ...
    };
    $('.demonstration [class*="col"] p').each(function () {
        var $this = $(this);
        $this.attr('title', translations[$this.text().replace(/\s+/g, '')]);
    });