user1321237
user1321237

Reputation:

How can I find an element ID when I only know the text inside the element with jQuery?

I have a form with id="main-form" and inside that there's a class="block-footer"

Inside that an element:

<button type="button">Submit</button>

How can I use jQuery to find this button without my adding an Id to the element? The button always has the text of Submit.

Is it worth using the id="main-form" as a starting point in my selection to make it more efficient?

Upvotes: 3

Views: 73

Answers (7)

Bob
Bob

Reputation: 1497

Since you already knew the form ID, you just have to loop each button element with and check if it contains Submit text.

    $(document).ready(function(){
        $("#main-form button").each(function(e){
             var btnCaption = $(this).text();
            if(btnCaption == 'Submit'){
                //do something
                alert('hey, i am the submit button');
            }
        });

    });

I've included a working example DEMO

Upvotes: 0

ShibinRagh
ShibinRagh

Reputation: 6646

you can manage this code

jQuery('document').ready(function() { jQuery('form').find('button').addClass('hi') });

Upvotes: 0

Mathias Bynens
Mathias Bynens

Reputation: 149564

Select all the <button> elements, then filter them based on their innerHTML:

$('button').filter(function() {
  return this.innerHTML == 'Submit';
});

If needed you can be more explicit by only selecting button elements with type="button", although this is slightly less efficient:

$('button[type="button"]').filter(function() {
  return this.innerHTML == 'Submit';
});

As for your comment:

Can I make it more efficient as I know that button is inside a div with a class I know and also inside my form with known ID?

Sure you can.

var $container = $('.element-that-contains-the-button');
$('button', $container).filter(function() {
  return this.innerHTML == 'Submit';
});

You could also use $container.find(), which has the exact same effect.

Upvotes: 3

Abadinis
Abadinis

Reputation: 21

Use the :contains selector.

This would work for your question:

$(":contains('Submit')").Action()

Upvotes: 0

Rob Rodi
Rob Rodi

Reputation: 3494

You can use the jquery Contains selector.

var yourButton = $('button:Contains("Submit")');

Upvotes: 0

sushil bharwani
sushil bharwani

Reputation: 30187

jQuery('#main-form button:contains("submit")') will give you buttons of type submit inside mainform having submit text.

Upvotes: 0

grc
grc

Reputation: 23565

This will select all the buttons containing the text "Submit".

$('button:contains("Submit")')...

Or if you know more about the element it can be found inside:

$('.block-footer button:contains("Submit")')...

Upvotes: 1

Related Questions