How do I find an item ID when I know only the text inside the item 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?

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.

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章