Friday, 11 April 2014

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.

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function ChangeInnerHTML()
{
//Iterate all the buttons with innerHTML = "Clicked" in the DOM and set them to "Click me".
}
</script>
</head>
<body>
<button type="button" id="myButton1">Click me</button>
<button type="button" id="myButton2">Clicked</button>
<button type="button" id="myButton3">Click me</button>
<button type="button" id="myButton4">Clicked</button>
<button type="button" id="myButton5">Click me</button>

<button type="button" id="btnChangeInnerHTML"      onclick="ChangeInnerHTML()">Change InnerHTML</button>

</body>
 </html>

 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");
}

No comments:

Post a Comment