How to change InnerHTML of all the HTML Buttons in one go using jQuery?
How to change InnerHTML of all the HTML Buttons in one go using jQuery?
Suppose, I have 5 buttons on my page. How can I change the innerHTML of the buttons in one go using jQuery? I want that buttons having text "Clicked" should get changed to "Click me" when Change InnerHTML button is clicked. I will use jQuery to solve this problem. Refer the following example.
function ChangeInnerHTML()
{
//Iterate all the buttons with innerHTML = "Clicked" in the DOM and set them to "Click me".
}
There are many approaches for doing this task.
Approach 1:
function ChangeInnerHTML() {
$('button').each(function() {
if ($.trim($(this).html()) == "Clicked")
$(this).html('Click me');
});
}
Approach 2:
Use Attribute selector in jquery.
function ChangeInnerHTML()
{
$("[id^=myButton]:contains('Clicked')").click(function() {
$(this).text("Click Me");
});
}
Approach 3:
function ChangeInnerHTML()
{
document.body.innerHTML=
document.body.innerHTML.replace(/Clicked/g,'Click me');
}
Approach 4:
Without jQuery
function ChangeInnerHTML()
{
var btns = document.querySelectorAll('button[id^=myButton]');
for (var i = 0; i < btns.length; i++) {
if (btns[i].innerHTML.trim() == 'Clicked') {
btns[i].innerHTML = 'Click Me'
}
}
}
Approach 5:
This will change the innerHTML of all the buttons.
function ChangeInnerHTML()
{
$("button[id*=myButton]").html("Click me");
}