0

I have this HTML code

 <div class="form-actions">
    <button type="submit" class="btn btn-success">I'm a button! Yayyy!</button> 
 </div>

I need to access that button in JS and click on it. And I cannot add an id to it, because it's on a webpage. (I'm using tampermonkey/greasemonkey btw)

1
  • Do you use JQuery as well? If yes, then you could write $(".btn.btn-success" ).click(); Commented Nov 15, 2015 at 20:42

2 Answers 2

1

This is quite easy to do using jQuery.

$('.btn.btn-success:contains("I\'m a button! Yayyy!")')

^ would be your button.

If there's no other buttons with this text, the solution can be narrowed down to:

$('button:contains("I\'m a button! Yayyy!")')

If there can be another buttons, containing this text, and you want to address the button, which exactly matches it, the solution would be

$(".btn.btn-success").each(function(){
    if($(this).html()=="I'm a button! Yayyy!"){
        //$(this) there is the button you want
    }
})
Sign up to request clarification or add additional context in comments.

3 Comments

Note that buttons with the text "I'm a button! Yayyy! Just kidding, I'm not." would be matched as well by this selector.
The second solution worked for me, the first one, no.
@Game made an edit: check the renewed first and second solutions. Every solution should work now. The previous second solution was actually invalid, sorry for that.
0

You could select all the button elements on the page and then use the .filter() method to filter them based on their .textContent property:

Example Here

var buttons = document.querySelectorAll('button');
var filteredButtons = Array.prototype.filter.call(buttons, function (el) {
    return el.textContent.trim() === 'Find based on this text.';
});

// Click the first button
filteredButtons[0].click();

Of course in your case, you can select all the .btn-success elements that are descendants of elements with class .form-actions:

var buttons = document.querySelectorAll('.form-actions .btn-success[type="submit"]');
var filteredButtons = Array.prototype.filter.call(buttons, function (el) {
    return el.textContent.trim() === 'Find based on this text.';
});

// Click the first button
filteredButtons[0].click();

1 Comment

If you only need the first button, you could use Array.prototype.some and in the callback when a match is found, assign the match to a variable and return true to stop iterating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.