Add CSS Class Property through Javascript - 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.

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.. :)

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

ClassName means "class name" (ms-crm-SelectBox) not "Entire selector". (querySelector and querySelectorAll let you use complete selectors though.
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.

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

Related

CSS selector for ALL elements with SAME CLASS after and before current element

I was looking here: CSS Selector for selecting an element that comes BEFORE another element?
...but wasn't able to find a correct answer for my issue.
Here is a fiddle example: https://jsfiddle.net/Munja/bm576q6j/3/
.test:hover, .test:hover + .test
With this, when I :hover element with .test class, I achieved to change style for current element with .test class and first next element with .test class.
What am I trying to achieve?
When I select any row/column (e.g agent 2), I want to apply same style for ALL elements with that same class (.test in this case).
If it is not possible to achieve this with css only, * I am willing to accept and other good solution.*
Thank you.
In your specific case you can use
tbody:hover > .test {
background: green;
}
fiddle: https://jsfiddle.net/bm576q6j/4/
Note that if you add more classes in the same tbody it will not give what you want. Check also this question: Hover on element and highlight all elements with the same class
So, after waiting for several more hours, I have decided to use JavaScript solution mentioned in answer from #BasvanStein. Posting it here as answer, to make things easier for someone else with same issue.
Here is a working fiddle: https://jsfiddle.net/Munja/bm576q6j/15/
var elms = document.getElementsByClassName("test");
var n = elms.length;
function changeColor(color) {
for(var i = 0; i < n; i ++) {
elms[i].style.backgroundColor = color;
}
}
for(var i = 0; i < n; i ++) {
elms[i].onmouseover = function() {
changeColor("red");
};
elms[i].onmouseout = function() {
changeColor("white");
};
}

How would I write this JQuery addClass method in vanilla js

So how exactly would i write
$('div').addClass('border1');
in Vanilla javascript, like what would my add class method look like. So far what I have is,
function addClass(x,y) {
x.className += " " + y;
}
but i know this is wrong, as the parameters are off. Im really lost.
Let's take a closer look at what jQuery does here.
What is the meaning of $('div')?
In jQuery terms it means "select all 'div' elements in the document".
$('div') is a jQuery object which represents all div elements in the document. But nowhere in this code you specifically target a single DOM element by yourself.
Let's write our own simplified selection object "MySelect":
/**
* `MySelect` object constructor.
*/
function MySelect(selector){
this.elementList = document.querySelectorAll(selector);
}
Now let's use it:
var divs = new MySelect('div');
divs.elementList; // all `div` elements in the document.
(Note that querySelectorAll is a native javascript DOM method)
Now that we have an elements selection object, let's add an addClass method to it:
/**
* Add the specified class to all elements selected by this object.
*/
MySelect.prototype.addClass = function(cls){
var i, e;
for (i = 0; i < this.elementList.length ; i++){
e = this.elementList[i];
e.className += " " + cls;
// can also use e.classList.add
}
}
And voila:
divs.addClass('xyz');
This, in a very simplified fashion, is how jQuery works.
For the $ syntax you can do:
function $(selector){
return new MySelect(selector);
}
And use it as usual:
$('div').addClass('xyz');
element.classList is vanillaJS's way of doing it
var x = document.getElementById('x');
var y = document.getElementById('y');
var z = document.getElementById('z');
y.addEventListener('click',function(){
x.classList.add('blue');
});
z.addEventListener('click',function(){
x.classList.toggle('blue');
});
#x {
width: 50px;
height: 50px;
border: 1px dotted gray;
}
.blue {
background-color: blue;
}
<div id="x"></div>
<button id="y">add the class</button>
<button id="z">toggle the class</button>
If you're targetting IE10+, you can use
var el = document.getElementById("someId");
el.classList.add(className);
For all browsers :
if (el.classList)
el.classList.add(className);
else
el.className += ' ' + className;
Source:
http://youmightnotneedjquery.com/#add_class
function addClass(selector, class) {
els = document.querySelectorAll(selector);
for (var i = 0; i < els.length; i++) {
els[i].className += class;
}
}
Then you can do:
addClass('div', 'border1');
addClass('#someID', 'someclass');
addClass('.someClass', 'someotherclass');
I write this not so much as a recommendation, but because you seem to want to create a method, rather than a function; presumably under the impression that one might be better. They're much the same, however, except extending the prototype to add a method can potentially cause trouble. However, if you must:
NodeList.prototype.addClass = function (cName) {
// creates an Array from the NodeList, and iterates through:
return [].forEach.call(this, function (elem) {
// adds the passed-in class-name:
elem.classList.add(cName);
});
};
The above can be called with:
document.querySelectorAll('div').addClass('newClassName');
Or:
document.getElementsByTagName('div').addClass('newClassName');
Note that this uses features found in relatively modern browsers, though they could be replaced with a for loop (forEach) and string-concatenation with className property (classList.add()) if desired.

How to get a style property from a css class and set it to another css class?

Is it somehow possible to get a style property from a css class that is not used anywhere?
I'd like to read for example the color property that I want to apply to an animation with jquery ui but I want to avoid duplicating them again in the js code.
Let's say I have this:
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<span class="current-style">Hello world!</span>
Now I would like to set the .default-style color to the .current-style and then animate the color from the .default-style to the .disabled-style and back on click but I don't know how to get them without creating a hidden element.
var currentColor = ""; // I'm stuck here. Get color from css class?
$("span.abc").animate({ color: currentColor });
You can cheat by creating an element, applying the class, adding the element to the document, getting its color, then removing it. If this is all done in one code block, the user will never see the element:
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
Alternately, you can loop through document.styleSheets in the document, and loop through the rules of each stylesheet looking for the one that uses that simple class selector, then look at the styles that rule defines.
Gratuitous snippet: ;-)
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
$("<p>The color is: " + color + " (the color of this paragraph)</p>").css("color", color).appendTo(document.body);
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="current-style">Hello world!</span>
Side note: jQuery's animate function doesn't animate colors natively, you need to add a plugin to do it (jQuery UI bundles one, but if you're not using jQuery UI, you can just use one of the plugins that does this, such as this one, directly).
Correct Way ! Without cheating the document
var currentColor;
var styleSheets = document.styleSheets;
for(var j=0; !currentColor && j<styleSheets.length; j++)
{
var styleSheet = styleSheets[j];
var cssprops = styleSheet.cssRules || styleSheet.rules; // .rules is for older IE
for (var i = 0; i < cssprops.length; i++) {
if(cssprops[i].selectorText == '.default-style');
currentColor = cssprops[i].style.getPropertyCSSValue('color').cssText;
}
}
$("span.abc").animate({ color: currentColor });
Reference From https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets

How to write css code in javascript? (Uncaught TypeError: Cannot set property "height" of undefined)

How to write css code in javascript? (Uncaught TypeError: Cannot set property "height" of undefined)
javascript
document.getElementById("slideshow").getElementsByClassName("arrow").style.height = "86px";
css
#slideshow .arrow{
height:86px;
width:60px;
position:absolute;
background:url('arrows.png') no-repeat;
top:50%;
margin-top: -43px;
cursor: pointer;
z-index: 5000;
}
The key here is the pluralisation of getElementsByClassName - elements. This method returns an array-like object of elements, not just one element.
To apply the style to each, you need to loop through this array-like object and add the styles to each individual element returned:
var elems = document.getElementById("slideshow").getElementsByClassName("arrow");
for (var i = 0; i < elems.length; i++)
elems[i].style.height = "86px";
document.getElementsByClassName returns an array.
You have to loop through it, or if you know the index, do this:
document.getElementById("slideshow").getElementsByClassName("arrow")[0].style.height = "86px";
or
document.getElementById("slideshow").getElementsByClassName("arrow")[i].style.height = "86px";
i being your loop variable.
A bit of theory:
Changing HTML Style
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
Here is the example:
// JavaScript demonstration
var changeBg = function (event) {
console.log("method called");
var me = event.target
, square = document.getElementById("square");
square.style.backgroundColor = "#ffaa44";
me.setAttribute("disabled", "disabled");
setTimeout(clearDemo, 2000);
}
function clearDemo(button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
var button = document.querySelector("button");
button.addEventListener("click", changeBg);
console.log(button);
#square {
width: 20em;
height: 20em;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
JavaScript-Based Style Sheets - http://www.w3.org/Submission/1996/1/WD-jsss-960822
Mozzila's Web Developer guide - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/JavaScript
While I've started with explanation and theory #James Donnelly already provided my answer, which I've wanted to use:
var elements = document.getElementById("slideshow").getElementsByClassName("arrow");
for (var i = 0; i < elems.length; i++) {
elems[i].style.height = "86px";
.
As someone already pointed out,
document.getElementsByClassName returns an array (N Objects)
while
document.getElementById returns an element (ONE object)
This is because N elements can have the same class but only ONE item can have a particular ID.
Since you can't edit more items' attribute at once, you must cycle them and edit the attribute of each one by one
document.getElementById("slideshow").getElementsByClassName("arrow")[0].style.height = "86px";
document.getElementById("slideshow").getElementsByClassName("arrow")[1].style.height = "86px";
document.getElementById("slideshow").getElementsByClassName("arrow")[2].style.height = "86px";
.....
document.getElementById("slideshow").getElementsByClassName("arrow")[N].style.height = "86px";
This can be achieved by using a for cycle or a each one.

Change CSS with javascript using getElementById

I do not know how to access a specific CSS using javascript.
Let us say,
#menu { color: red; }
can be accessed by
document.getElementById('menu').style.color = "blue";
But I want to access
#menu li a { height: 10%; }
How do I access that using document.getElementById() ?
Plain JavaScript solution:
You cannot use getElementById() in this case since its purpose is only to query id attributes, but you can use getElementsByTagName() in context of #menu:
var m = document.getElementById('menu');
// Get all <li> children of #menu
var lis = m.getElementsByTagName('li');
// Loop over them
for (var i=0; i<lis.length; i++) {
// Get all <a> children of each <li>
var atags = lis[i].getElementsByTagName('a');
for (var a = 0; a<atags.length; a++) {
// And set their color in a loop.
atags[a].style.color = 'blue';
// or change some other property
atags[a].style.height = '25%';
}
}
jQuery Solution:
If you are able to use jQuery, this becomes exceedingly simpler:
$('#menu li a').css('color', 'blue');
You don't; you'd have to find all the <a> tags that matched that criteria.
The .getElementById() function is about getting an element by a unique "id" string. If you need to get elements otherwise, there are other APIs to use: .getElementsByTagName(), .getElementsByClass(), .querySelectorAll(), etc. Browser support varies, and even .getElementById() is different between IE and other browsers.

Categories