How to Apply a CssClass to a series of similar objects with a different ID

I have a large application in which I have lots of Submit - Delete - Cancel - Add and .. buttons. All of them use a same .Button CssClass.

I decided to reach the interface so that I want to differise buttons interface.

How to Apply a CSSClass to a series of similar objects with a different ID

I should Have similar Delete / Submit / Cancel or ... Button interface all over the application

All of the Delete button id are btnDelete and the same for the rest. (btnSubmit - btnCancel ...)

Note that they are Asp control so that only the last part of their name are btnDelete or ... and before Name, you have a client ID like (MainPage_MainControl_TheSimpleForm_btnDelete)

Answers


The pure CSS way to do this would be a substring selector:

[id$="btnDelete"] { /* delete button styles */ }
[id$="btnSubmit"] { /* submit button styles */ }
[id$="btnCancel"] { /* cancel button styles */ }

These match any elements with an id attribute which ends in btnDelete, btnSubmit and btnCancel respectively. Unfortunately these are not supported by IE8 so you'd need to have a jQuery fallback.


Use the common class you declared:

.Button {
  /* applies to all buttons */
}

If you want to select a group buttons, you can add more styles separated by space.

<button class="Button AddButton" id="AddButton1">Add</Button>

CSS

.AddButton {
  /* only applies to add buttons */
}

Edit:

After clarification we need to add classes without changing the original HTML. How about looping over the elements and assign an additional class depending on the id.

var buttons = document.getElementsByTagName('button');

for (var i = 0; i < buttons.length; i++) {
    var btn = buttons[i];
    if (btn.id.indexOf('btnAdd') > 0) {
       btn.className = btn.className + ' ButtonAdd'; // the space is important
    } else if (btn.id.indexOf('btnDelete') > 0) {
       btn.className = btn.className + ' ButtonDelete'; // the space is important
      ...
    }
}

And if you need to do this programatically at runtime, you could always use JQuery and the AddClass method. To handle partial ID match, take a look at the Attribute Contains documentation.

$('[ID*="btnDelete"]').AddClass("newCSSClassToAdd")

Need Your Help

insert multiple rows along with static values

sql sql-server tsql insert rows

I'm very new to SQL. More familiar with procedural programming

SQL: Persisting a root_id in a three-level tree?

sql postgresql self-join adjacency-list

I have a simple three-level tree, currently stored as an adjacency list:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.