Azeem
Azeem

Reputation: 2924

Add CSS Class Property through Javascript

I have an HTML page having css class for a control with following definition:

.ms-crm-Inline-Edit select.ms-crm-SelectBox {
border: 1px solid #CCCCCC;
font-size: 12px;
margin: 1px 0 0 1px;
width: 100%;
}

I need to add a new attribute to this class as follows:

height: "120px !important";

This has to be done through Javascript. I can't modify origional class definition that's why I have to add Javascript function which does this job. For that purpose I have written Jscript method but its not working.

function CustomizePicklistHeight ()
{
   document.getElementsByClassName('ms-crm-Inline-Edit select.ms-crm-SelectBox').style.height = '120px !important';
}

I guess, first we have to add height attribute to this class but I dont know how to do that in JScript. Please suggest.

Upvotes: 1

Views: 302

Answers (4)

kunl
kunl

Reputation: 1195

document.getElementsByClassName returns an array of all items with that class.

Try this:

function CustomizePicklistHeight()
{

// Store elements for each class differently. Just in case :)

var elements1 =  document.getElementsByClassName('ms-crm-Inline-Edit');
var elements2 =  document.getElementsByClassName('ms-crm-SelectBox');

// Since you cant affect the array directly, you use a loop to do the operation on each individual element

for (var i = 0; i < elements1.length; i++)
{
element1[i].style.height = '120px !important';
};

for (var j = 0; j < elements2.length; j++)
{
element1[j].style.height = '120px !important';
};

}​

Hope this helps.. :)

Upvotes: 2

psx
psx

Reputation: 4048

  var matches = document.querySelectorAll(".ms-crm-Inline-Edit, select.ms-crm-SelectBox");
  for(i=0; i<matches.length; i++)
  {
    matches[i].style.height = '120px !important';
  }

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Upvotes: 1

Paulo Lima
Paulo Lima

Reputation: 1238

you will have to make a loop by setting each item, and if you have not "! important" earlier you do not need it.

Upvotes: 0

Quentin
Quentin

Reputation: 943108

  1. ClassName means "class name" (ms-crm-SelectBox) not "Entire selector". (querySelector and querySelectorAll let you use complete selectors though.
  2. Elements means "elements" (plural) not "Element". It returns a NodeList, which you can loop over like an array.

If, on the other hand, you want to the modify the CSS rule-set instead of the styles applied directly to the HTML elements, then you need to look at document.styleSheets instead.

Upvotes: 0

Related Questions