abacusit
abacusit

Reputation: 53

How to select buttons by the text/html in jQuery?

I'm trying to select buttons by the text/html that appears on the button but with not success:

There are multiple button sets like this in my page:

<button>Save</button>
<button>Add</button>
<button>Cancel</button>

I've used the following:

$('button[value=Save]')
$('button[html=Save]')
$('button[innerHTML=Save]')
$('button[text=Save]')

But none of them works. Can someone help please?

Upvotes: 0

Views: 65

Answers (3)

Kamil Szymański
Kamil Szymański

Reputation: 950

Possibly navigating trough all of them is the solution:

$(function() {
    var buttons = $('button');
    buttons.each(function() {
        if( $(this).html() == "Save" ) {
            $(this).attr('style', 'background: red');
        };
    });
});

http://jsfiddle.net/tqk6wuhu/

Upvotes: 0

mehulmpt
mehulmpt

Reputation: 16577

This should work:

1: On selection of index

$('button').eq(0) // will select first

2: On selection of value

for(i=0;i<$('button').length;i++) {
   if($('button').eq(i).text() == 'Your text') {
       var myBtn = $('button').eq(i);
       break;
   }
}

$(myBtn).doSomething();

Upvotes: 0

Vladimirs
Vladimirs

Reputation: 8599

You need to use :contains() selector like:

$("button:contains('Save')");

Upvotes: 2

Related Questions