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?
-
1show what you've triedKoosh– Koosh2018-10-05 19:40:32 +00:00Commented Oct 5, 2018 at 19:40
-
1Hey 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.Tyler Roper– Tyler Roper2018-10-05 19:41:15 +00:00Commented Oct 5, 2018 at 19:41
-
reason you do not add classes?epascarello– epascarello2018-10-05 20:14:00 +00:00Commented 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.skwagoner– skwagoner2018-10-08 03:08:13 +00:00Commented Oct 8, 2018 at 3:08
3 Answers
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:
......
}
});
});
Comments
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
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.