简体   繁体   中英

Javascript change button text by value

Maybe I'm not googling right but I have a simple question that I was not able to find an answer. I have a group of buttons with specific text. Because the page is dynamic depending on the user choices there may be five buttons cut for example.

 <button>Cut</button> <button>Copy</button> <button>Speak</button> <button>Fullscreen</button>

Above you can see one group but there might be the same buttons copied 10 times. I want to change the text of those buttons by getting their value. For example:

Getting all buttons with text "Cut" and change their value to "foo"

Then I want to do something similar with other text to the other buttons. How to do that?

Use document.querySelectorAll to select all the buttons and iterate through them using forEach loop. Check their text using textContent and if it is Cut set it to foo

 document.querySelectorAll('button').forEach((e)=>e.textContent=='Cut'?e.textContent="foo":false)
 <button>Cut</button> <button>Copy</button> <button>Cut</button> <button>Speak</button> <button>Cut</button> <button>Fullscreen</button> <button>Cut</button>

I would suggest getting all the buttons using document.getElementsByTagName() and filtering based on the content. Then you can iterate over your filtered array and perform whatever modifications you want:

// get all buttons as an array
const buttons = Array.from(document.getElementsByTagName("button"));

// filter the array using a strict string equality check
const cutButtons = buttons.filter(button => button.textContent === "Cut");

// perform your modifications
cutButtons.forEach(button => {
   button.textContent = "foo";
});

You can use querySelectorAll() to get all the buttons. Then loop through them to check the textContent to modify the button:

 var btn = [].slice.call(document.querySelectorAll('button')); btn.forEach(function(b){ if(b.textContent == 'Cut') b.textContent = 'foo'; });
 <button>Cut</button> <button>Copy</button> <button>Speak</button> <button>Fullscreen</button> <button>Cut</button>

Get buttons by tag name using getElementsByTagName() then with in for loop check content and change it if "Cut" using Node.textContent

var cut=document.getElementsByTagName("button");
    for(var i=0;i<cut.length;i++){
        if(cut[i].textContent=="cut"){
            cut[i].textContent="foo"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM