Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery change all elements text

I need jquery to change numbers in all of pages. for example i want change 1 to ۱ so i tried this way:

$("*").each(function(){
    $(this).html(  $(this).html().replace(1,"۱")  );
})

but this will change css rules and attributes also. is there any trick to escape css and attributes?

like image 562
ShirazITCo Avatar asked Dec 13 '22 14:12

ShirazITCo


2 Answers

This isn't a job that jQuery naturally fits into. Instead of getting jQuery to fetch a flat list of all elements, recursively traverse through the DOM tree yourself, searching for text nodes to perform the replace on.

function recursiveReplace(node) {
    if (node.nodeType === Node.TEXT_NODE) {
        node.nodeValue = node.nodeValue.replace("1", "۱");
    } else if (node.nodeType == Node.ELEMENT_NODE) {
        $(node).contents().each(function () {
            recursiveReplace(this);
        });
    }
}

recursiveReplace(document.body);

See it in action here.

like image 123
David Tang Avatar answered Dec 30 '22 20:12

David Tang


Try this:

$("body *").each(function() { 
    if ( this.childElementCount > 0 ) { return; }
    $(this).text(function(i, v) { return v.replace('1','۱'); }); 
});

Update: doesn't work...

like image 36
Šime Vidas Avatar answered Dec 30 '22 20:12

Šime Vidas