How to correctly loop querySelectorAll for hyperlink translation (JavaScript)

38 Views Asked by At

Hello!

Am working on an author's hyperlink translation in several languages.

Could someone help me correctly loop querySelectAll which translates some text for all elements collected by it, because it only translates the first hyperlink and not them all.

switch (pLang) {
    
    case "lv":        
        document.querySelectorAll('[title="John Davis publikācijas"]').innerHTML = "Džons Deivis";
    break;
    
    case "ru":        
        document.querySelectorAll('[title="Записи John Davis"]').innerHTML = "Джон Дэйвис";
    break;
}
1

There are 1 best solutions below

2
On

You could use a forEach to modify all the elements instead of just the first one:

switch (pLang)
{
    case "lv":        
        [... document.querySelectorAll('[title="John Davis publikācijas"]')].forEach((element)=>
        {
            element.innerHTML = "Džons Deivis";
        });
    break;
    
    case "ru":        
        [... document.querySelectorAll('[title="Записи John Davis"]')].forEach((element)=>
        {
            element.innerHTML = "Джон Дэйвис";
        });
    break;
}