2

I need to target and override CSS styles on buttons. I would like to change styles based on the contents of the button. For example if the button text is "Cancel" I would like to overwrite the CSS to a different set of styles. How can I do this in jQuery?

4
  • 1
    show what you've tried Commented Oct 5, 2018 at 19:40
  • 1
    Hey skwagoner, and welcome to SO. Please edit your question to include any attempts you've made. While asking us "Why doesn't this specific piece of code work?" is perfectly acceptable, asking "I want this. How do I do it?" is much too broad. Commented Oct 5, 2018 at 19:41
  • reason you do not add classes? Commented Oct 5, 2018 at 20:14
  • Unfortunately, I have not tried any thing since I do not know jQuery, yet. I'm working on an app where I cannot touch the HTML and have to work with the classes that are already there. Commented Oct 8, 2018 at 3:08

3 Answers 3

1

Assume that need to change the Css buttons on Loading page

$(document).ready(function(){
    $('input[type=button]').each(function() {
        var content = $(this).text();
        switch (content) {
        case "Cancel": 
          $(this).addClass('cancelClass');
        case "Success":
          $(this).addClass('SuccessClass');
        case 3: 
          ......
       }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Probably the best way to do what you need is to remove the inline style of the button which has the value = "Cancel" with the

removeAttr() 

function and then use the

css() 

function to apply the styles.

The result should be this:

$('input[type="button"][value="Cancel"]').removeAttr('style').css("whatever");

and 'whatever' obviusly substituted by your style.

Comments

0

jQuery has a selector that searches for strings of text :contains(). If we utilize this specifically for your example, you can set the selector to search for any instance of <button> with the text "Cancel", then apply a .css() function to change any CSS property you need to.

An example would be:

$( "button:contains('Cancel')" ).css( "background-color", "green" );

Note that the :contains() is case-sensitive, so keep that in mind.

Source: https://api.jquery.com/contains-selector/

1 Comment

—I'm new to jQuery but this looks like it will work. I will try and let you know.

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.