is it possible to remove a CSS property of an element using JavaScript ?
e.g. I have div.style.zoom = 1.2,
now i want to remove the zoom property through JavaScript ?
You have two options:
OPTION 1:
You can use removeProperty method. It will remove a style from an element.
el.style.removeProperty('zoom');
OPTION 2:
You can set it to the default value:
el.style.zoom = "";
The effective zoom will now be whatever follows from the definitions set in the stylesheets (through link and style tags). So this syntax will only modify the local style of this element.
removeProperty will remove a style from an element.
Example:
div.style.removeProperty('zoom');
MDN documentation page:
CSSStyleDeclaration.removeProperty
div.style.removeProperty('zoom');
element.style.height = null;
output:
<div style="height:100px;">
// results:
<div style="">
You can use the styleSheets object:
document.styleSheets[0].cssRules[0].style.removeProperty("zoom");
Caveat #1: You have to know the index of your stylesheet and the index of your rule.
Caveat #2: This object is implemented inconsistently by the browsers; what works in one may not work in the others.
You can try finding all elements that have this class and setting the "zoom" property to "nothing".
If you are using jQuery javascript library, you can do it with $(".the_required_class").css("zoom","")
Edit: Removed this statement as it turned out to not be true, as pointed out in a comment and other answers it has indeed been possible since 2010.
False: there is no generally known way for modifying stylesheets from JavaScript.
You can also do this in jQuery by saying $(selector).css("zoom", "")
This should do the trick - setting the inline style to normal for zoom:
$('div').attr("style", "zoom:normal;");
actually, if you already know the property, this will do it...
for example:
var txt = "";
txt = getStyle(InterTabLink);
setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");
function setStyle(element, styleText){
if(element.style.setAttribute)
element.style.setAttribute("cssText", styleText );
else
element.setAttribute("style", styleText );
}
/* getStyle function */
function getStyle(element){
var styleText = element.getAttribute('style');
if(styleText == null)
return "";
if (typeof styleText == 'string') // !IE
return styleText;
else // IE
return styleText.cssText;
}
Note that this only works for inline styles... not styles you've specified through a class or something like that...
Other note: you may have to escape some characters in that replace statement, but you get the idea.
To change all classes for an element:
document.getElementById("ElementID").className = "CssClass";
To add an additional class to an element:
document.getElementById("ElementID").className += " CssClass";
To check if a class is already applied to an element:
if ( document.getElementById("ElementID").className.match(/(?:^|\s)CssClass(?!\S)/) )
Related
What I currently have in my JS file:
if (documentElement.className("child") != -1){
documentElement.className("child").backgroundColor="red";
}
Basically as the title implies, I want all the classes with the name "child" on the page to change their background color to red.
className returns a string with all of the classes on the element. You need to see if that string contains your class:
if (documentElement.className.indexOf("child") != -1){
Use indexOf
Regarding what #Roberrrt said - you can achieve this simply selecting the 'child class' and applying a style to it.
For a visual example.
http://codepen.io/anon/pen/GNMJjr
In your code:
documentElement.className("child").backgroundColor="red";
That wouldn't work, this is a better way of achieving what you want:
document.querySelector('.child').style.backgroundColor = "red";
I still recommend using CSS. This is redundant and extremely verbose.
Try this maybe (tested on about:blank page with 5 <div> with 2 of them with the class="red" :
var red = [];
red = document.querySelectorAll(".red");
for (var i = 0; i < red.length; i += 1) {
red[i].style.backgroundColor = "red";
}
If you really want to verify if the class name contains a string, use classList.contains (it often have resolved this kind of problem for me, check the MDN page)
Please bear with the pseudocode and formatting, I can't really remember the code off the top of my head.
In IE9 and below, I know you could set properties and attributes by using the setAttribute() method, but that seems to have been changed in IE10 by a separating attributes and properties separately.
Even doing something like
element.setAttribute("className", "myClass");
sets the element to appear as
<tag className = "myClass" />
which doesn't even set the property.
In my code, I have a JSON list that I use to store the names and values of the attributes/properties, which I simply set with setAttribute();
createElement(tag, list)
{
//pseudocode
var element = createElementWithTag(tag);
for each(attr in attributes)
if (attributes.hasOwnKey(attr))
element.setAttribute(attr, attributes[attr]);
}
And this worked fine for IE7-9, but completely fails in IE10.
Is there some way that I can set the property and attribute without which type (attr or prop) it is?
I can't even think of a way to set the property dynamically, without hardcoding a case for which property I want to change.
A solution would probably also be helpful.
i think something like this is what you want:
function tag(tag, attribs) {
if(tag.charAt) tag = document.createElement(tag);
var alias = {
htmlFor: "for",
className: "class"
}, prop;
for (prop in attribs) if (attribs.hasOwnProperty(prop)) {
if("style" == prop) tag.style.cssText = attribs[prop];
try {
tag[prop] = attribs[prop];
} catch (h) {
tag.setAttribute( alias[prop] || prop, attribs[prop]);
}
}
return tag;
}
//test it:
tag("a", {href:"/", target:"_blank", innerHTML:" some text ", className: "1 2 3"}).outerHTML
tested in IE8 and Chrome.
if anyone knows of more dom->attrib mappings (like htmlFor), please edit them into the answer, thanks!
I know that altering element's style via JavaScript directly will cause a reflow. However, I was wondering if it is possible to alter multiple style values in a batch with only one reflow?
Not directly but there are some good suggestions on minimising the impact of reflows here:
http://dev.opera.com/articles/view/efficient-javascript/?page=3
In short, try something like this:
The second approach is to define a new
style attribute for the element,
instead of assigning styles one by
one. Most often this is suited to
dynamic changes such as animations,
where the new styles cannot be known
in advance. This is done using either
the cssText property of the style
object, or by using setAttribute.
Internet Explorer does not allow the
second version, and needs the first.
Some older browsers, including Opera
8, need the second approach, and do
not understand the first. So the easy
way is to check if the first version
is supported and use that, then fall
back to the second if not.
var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
'color: ' + newColor + ';' +
'border: ' + newBorder + ';';
if( typeof( posElem.style.cssText ) != 'undefined' ) {
posElem.style.cssText = newStyle; // Use += to preserve existing styles
} else {
posElem.setAttribute('style',newStyle);
}
You could put all the styles in a CSS class
.foo { background:#000; color:#fff; ... }
and then assign it to the className property
// javascript
var your_node = document.getElementById('node_id');
your_node.className = 'foo'
That should trigger only one repaint/reflow
use:
document.getElementById('elemnt_ID').setAttribute('style','color:white; margin:5px;');
If you were using jQuery, it has a .css function that allows you to add multiple style at once:
$('element').css({'color':'red', 'border':'#555 solid thin'});
You could set the element's visibility to 'hidden', then apply the styles and then make it visible again.
Instead of individually calling $("#item").removeClass() for every single class an element might have, is there a single function which can be called which removes all CSS classes from the given element?
Both jQuery and raw JavaScript will work.
$("#item").removeClass();
Calling removeClass with no parameters will remove all of the item's classes.
You can also use (but it is not necessarily recommended. The correct way is the one above):
$("#item").removeAttr('class');
$("#item").attr('class', '');
$('#item')[0].className = '';
If you didn't have jQuery, then this would be pretty much your only option:
document.getElementById('item').className = '';
Hang on, doesn't removeClass() default to removing all classes if nothing specific is specified? So
$("#item").removeClass();
will do it on its own...
Just set the className attribute of the real DOM element to '' (nothing).
$('#item')[0].className = ''; // the real DOM element is at [0]
Other people have said that just calling removeClass works - I tested this with the Google jQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:
$("#item").removeClass();
Of course.
$('#item')[0].className = '';
// or
document.getElementById('item').className = '';
Remove specific classes:
$('.class').removeClass('class');
Say if element has class="class another-class".
The shortest method
$('#item').removeAttr('class').attr('class', '');
You can just try:
$(document).ready(function() {
$('body').find('#item').removeClass();
});
If you have to access that element without a class name, for example you have to add a new class name, you can do this:
$(document).ready(function() {
$('body').find('#item').removeClass().addClass('class-name');
});
I use that function in my project to remove and add classes in an HTML builder.
I like using native JavaScript to do this, believe it or not!
solution 1: className
Remove all class of all items
const items = document.querySelectorAll('item');
for (let i = 0; i < items.length; i++) {
items[i].className = '';
}
Only remove all class of the first item
const item1 = document.querySelector('item');
item1.className = '';
solution 2: classList
// remove all class of all items
const items = [...document.querySelectorAll('.item')];
for (const item of items) {
item.classList.value = '';
}
// remove all class of the first item
const items = [...document.querySelectorAll('.item')];
for (const [i, item] of items.entries()) {
if(i === 0) {
item.classList.value = '';
}
}
// or
const item = document.querySelector('.item');
item.classList.value = '';
jQuery ways (not recommended)
$("#item").removeClass();
$("#item").removeClass("class1 ... classn");
refs
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
$('#elm').removeAttr('class');
Attribute "class" will no longer be present in "elm".
Since not all versions of jQuery are created equal, you may run into the same issue I did, which means calling $("#item").removeClass(); does not actually remove the class (probably a bug).
A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.
document.getElementById("item").removeAttribute("class");
Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.
This jQuery filter will remove the class "highlightCriteria" only for
the input or select fields that have this class.
$form.find('input,select').filter(function () {
if((!!this.value) && (!!this.name)) {
$("#"+this.id).removeClass("highlightCriteria");
}
});
Try with removeClass.
For instance:
var nameClass=document.getElementsByClassName("clase1");
console.log("after", nameClass[0]);
$(".clase1").removeClass();
var nameClass=document.getElementsByClassName("clase1");
console.log("before", nameClass[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clase1">I am a Div with class="clase1"</div>
I had a similar issue. In my case, on disabled elements was applied that aspNetDisabled class and all disabled controls had wrong colors. So, I used jQuery to remove this class on every element/control I want and everything works and looks great now.
This is my code for removing aspNetDisabled class:
$(document).ready(function () {
$("span").removeClass("aspNetDisabled");
$("select").removeClass("aspNetDisabled");
$("input").removeClass("aspNetDisabled");
});
I need to find random nodes according to random attribute values.
To do that I use getAtrribute on nodes from getElementsByTagName.
It seems like when I look for class name as attribute it does not work on IE (works on FF).
Anyone know if getAtrribute doesn't work only on 'class' or other attributes as well? (if its only class I'll do a workaround.)
It's worth testing all of your Javascript cross-platform, if you're not using something like jQuery to take the pain away, but Class may just be a special case.
This should be a cross-platform way of getting the class:
element.className
Anyone know if getAtrribute doesn't work only on 'class' or other attributes as well?
It fails for all attributes where the HTML attribute name differs from the DOM property name (className, htmlFor), plus you have to use the DOM-style capitalisation. It also returns the wrong datatype for attributes whose DOM properties aren't strings:
disabled, readOnly, checked, selected, multiple,
compact, declare, isMap, noHref, defer, noResize,
size, cols, rows, width, height, hspace, vspace,
maxLength, tabIndex, colSpan, rowSpan
and possibly others I've missed!
element.getAttribute(x)
in IE is exactly the same as saying:
element[x]
So in general you should avoid using getAttribute, and use the simple DOM Level 1/2 HTML interfaces such as ‘element.className’ instead.
This is finally fixed in IE8.
IE is broken in this respect. You can access the class in IE via getAttribute("className") but of course this isn't really the attribute so it doesn't work in !IE.
That leaves you with a choice of branching to get element.className or branching to getAttribute on "className" or "class". Not good.
You can grab a list of all attributes from your elements and test their value that way. This snippet handles both IE and WebKit browsers, and will return the string value of the CSS class:
var value = "";
var elements = document.getElementsByTagName("div");
for(var i = 0; i < elements.length; i++){
if(typeof elements[i].attributes['class'] == "undefined"){
value = elements[i].getAttribute("class");
} else {
value = elements[i].attributes['class'].nodeValue;
}
alert(value); // careful, this will be a lot of alerts
}
Here you can get and set the class attribute with cross browser compatibility.
//also works with IE7 and below
//get class attribute value
var class_name = document.getElementById('elem_id').className;
//set class attribute
document.getElementById('elem_id').className = 'new-class-name';