setAttribute is not working for 'style' attribute on IE - javascript

I'm porting a piece of JS code written for Firefox into Internet Explorer. I faced a problem of changing style of an element using setAttribute method which was working on Firefox.
button.setAttribute('style', 'float: right;');
I tried setting the style member of button and it didn't work either. This was the solution in case of setting onclick event handler.
button.style = 'float: right;';
First I wanna know the solution for the above problem and
Second are there any maintained lists for these differences between browsers ?

Because style itself is an object. What you want is:
button.style.setAttribute('cssFloat','right');
But IE doesn't support setAttribute for style objects. So use the fully cross-browser supported:
button.style.cssFloat = 'right';
As for reference, I always go to www.quirksmode.org . Specifically: http://www.quirksmode.org/compatibility.html . Click on all the DOM related stuff.
And finally, to set multiple attributes I usually use something like:
function setStyle(el,spec) {
for (var n in spec) {
el.style[n] = spec[n];
}
}
usage:
setStyle(button,{
cssFloat : 'right',
border : '2px solid black'
});
Note: object.attribute = 'value' although works in all browsers may not always work for non-HTML DOM objects. For example, if your document contains embedded SVG graphics that you need to manipulate with javascript you need to use setAttribute to do it.

You need to use cssText
button.style.cssText = 'float: right;';

getAttribute and setAttribute are broken in Internet Explorer.
The correct syntax for what you are trying to achieve is:
button.style.cssFloat = 'right';
The correct solution to the problem is more likely to be:
button.className = 'a class that matches a pre-written CSS rule-set';

I noticed that setAttribute works in IE only when the attribute does not already exist.
Therefore, use remove attribute and then use set attribute.
Haven't tested this for bugs, but conceptually I think this will work:
NOTE - this was written to exist inside object that had property called 'element'.
//Set Property
this.setProperty = function (a, b) {
var c = this.element.getAttribute("style");
var d;
if (!c) {
this.element.setAttribute("style", a + ":" + b);
return;
} else {
d = c.split(";")
}
for (var e = 0; e < d.length; e++) {
var f = d[e].split(":");
if (f[0].toLowerCase().replace(/^\s+|\s+$/g, "").indexOf(a.toLowerCase().replace(/^\s+|\s+$/g, "")) == 0) {
d[e] = a + ":" + b
}
}
d[d.length] = a + ":" + b;
this.element.setAttribute("style", d.join(";"))
}
//Remove Property
this.removeProperty = function (a) {
var b = this.element.getAttribute("style");
var c;
if (!b) {
return
} else {
c = b.split(";")
}
for (var d = 0; d < c.length; d++) {
var e = c[d].split(":");
if (e[0].toLowerCase().replace(/^\s+|\s+$/g, "").indexOf(a.toLowerCase().replace(/^\s+|\s+$/g, "")) == 0) {
c[d] = ""
}
}
this.element.removeAttribute("style");
this.element.setAttribute("style", c.join(";").replace(";;", ";"))
}

Another useful way to mutate a style property is using the square brackets to access the property. This is useful for accessing properties which because of their name would give a syntax error if expressed normally. In JavaScript it is perfectly permissible to have properties with numeric values, numeric first letters and symbols and spaces as characters, but then you must use the square bracket way of accessing properties.
node.style.z-index = 50;//Firefox says error, invalid assignment left hand side.
node.style["z-index"] = "50";//Works without error

It does work in IE. Just tried it out.
The method is passed a style name and a value
The method then checks to see if there are any styles
If no styles attribute exists, then the method simply sets the style and stops
If a style attribute exists, all the styles in the attribute are split into an array
The array is iterated and all applicable style definitions are updated with the new value
The style attribute is then removed from the element
The style attribute is added back to the element with its values set to the new info
gathered from the array

Related

Why is my js returning an empty string when I check the background colour of an element? [duplicate]

I am looking for a way to retrieve the style from an element that has a style set upon it by the style tag.
<style>
#box {width: 100px;}
</style>
In the body
<div id="box"></div>
I'm looking for straight javascript without the use of libraries.
I tried the following, but keep receiving blanks:
alert (document.getElementById("box").style.width);
alert (document.getElementById("box").style.getPropertyValue("width"));
I noticed that I'm only able to use the above if I have set the style using javascript, but unable to with the style tags.
The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.
The two ways have differences, for example, the IE element.currentStyle property expect that you access the CCS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc).
Also, the IE element.currentStyle will return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.
I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...) notation, on IE they will return them as they were defined.
I'm currently working on an article in the subject, you can follow the changes I make to this function here.
I believe you are now able to use Window.getComputedStyle()
Documentation MDN
var style = window.getComputedStyle(element[, pseudoElt]);
Example to get width of an element:
window.getComputedStyle(document.querySelector('#mainbar')).width
In jQuery, you can do alert($("#theid").css("width")).
-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.
Update
for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.
Use getComputedStyle function, Computed style contains all the CSS properties set to an element. Even if do not set a property to an element. You will still find that property in the computed styles.
Example:
<style>
#Body_element {
color: green;
}
</style>
<body id="Body_element">
<script>
alert(getComputedStyle(Body_element).color)
</script>
</body>
This is a helper function if you want to get multiple style rules from the same element.
You pass it the element and the styles you want as arguments, and it will return their values
const convertRestArgsIntoStylesArr = ([...args]) => {
return args.slice(1);
}
const getStyles = function () {
const args = [...arguments];
const [element] = args;
let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);
const styles = window.getComputedStyle(element);
const stylesObj = stylesProps.reduce((acc, v) => {
acc[v] = styles.getPropertyValue(v);
return acc;
}, {});
return stylesObj;
};
Now, you can use this function like this:
const styles = getStyles(document.body, "height", "width");
OR
const styles = getStyles(document.body, ["height", "width"]);

Trying to make div background change color when 2 ids are true

I am trying to make each div's background change color when 2 ids exist. it is not changing the color. I cannot figure out what I am doing wrong. I am brand new to javascript. I have an embedded stylesheet and dont know if the javascript will override the css.
Also, I know some PHP and want to 'echo' the variables throughout the program so that I can see what the string value is in order to debug my own code. what is the easiest way to do this?
function drop(ev){
ev.preventDefault();
var image = ev.dataTransfer.getData("content");
ev.target.appendChild(document.getElementById(image));
var mydiv = '';
for (var i=0;i<9;i++)
{
if ($('#target'.i).find('#answer'.i).length == 1)
{
mydiv = document.getElementById('target'+i);
mydiv.style.backgroundColor = '#00CC00';
}
else
{
mydiv = document.getElementById('target'+i);
mydiv.style.backgroundColor = '#FF0000';
}
}
}
I think your problem may be on this line you have . not + to build the id's correctly.
if ($('#target'.i).find('#answer'.i).length == 1)
so your code should be:
if ($('#target'+i).find('#answer'+i).length == 1)
Keeping in mind I'm no jQuery wizard, my first notion was something like this:
$('div[id^=target]').each(function() {
var el = $(this).find('div[id^=answer]').addBack();
el.css('backgroundColor', el.length > 1 ? '#00CC00' : '#FF0000');
});
...but then I noticed that unlike your example, I was changing both the parent and child div. Something like this might be closer to your intent:
$('div[id^=target]').css('backgroundColor', function () {
return $(this).find('div[id^=answer]').length ? '#00CC00' : '#FF0000';
});
You also could retain the for loop if that's your preference:
for (var i = 0; i < 9; ++i) {
$('div#target' + i).css('backgroundColor', function() {
return $(this).find('div#answer' + i).length ? '#00CC00' : '#FF0000';
});
}
...and, just for fun, something kinda esoteric:
$('div[id^=target]:has(div[id^=answer])').css('backgroundColor', '#00CC00');
$('div[id^=target]:not(:has(div[id^=answer]))').css('backgroundColor', '#FF0000');
Fiddle!
Your code should work (see fiddle) with the correct operator for concatenation, i.e. with + instead of ., however here are a few points you should bear in mind :
Point 1 :
Among all the i variables you're iterating over in your for loop, if there is no div with id equal to "target" + i you will end up in the following else block :
else
{
mydiv = document.getElementById('target'+i); // null
mydiv.style.backgroundColor = '#FF0000';
}
At that place mydiv will be null and mydiv.style will throw an error.
Point 2 :
It seems you used jQuery to find the answers elements, while you used document.getElementById, which is part of the DOM API, to select then the target element. It would have been more consistent to use jQuery there too.
Point 3 :
If you want to simply output the value of some variable you can use console.log, which will output in the javascript console of the browser. The console object is provided by the browser, therefore you may not have the console.log method, but if you are using an up to date browser there is a good chance you will have it.
To summarize, see this fiddle for an example that takes these points into account.

Javascript: add an inline style to elements in a page that have a specific computed style attribute

I'm trying to add an inline style to elements in a page that have a specific computed style attribute.
For instance:
<head>
<style>
p.mim {
cursor:pointer;
}
a.fif {
cursor:pointer;
}
</style>
</head>
<body>
<p class="mim">prova</p>
<a class="fif">prova</a>
</body>
I want to add an inline style "cursor:wait" to each element that has "cursor:pointer" set in the computed style:
<body>
<p class="mim" style="cursor:wait;">prova</p>
<a class="fif" style="cursor:wait;">prova</a>
</body>
This is what I tried:
var elms = document.getElementsByTagName("*");
for (var j = 0; j < elms.length; j++) {
var crs = getComputedStyle(elm, null).getPropertyCSSValue('cursor') || "";
crs = crs.replace(/\s/g, "").toLowerCase();
switch (crs) {
case "pointer":
case "Pointer":
case "POINTER":
elm.style.cursor = "wait";
break;
}
});
Your code is redundant for several reasons, and incomplete for others.
Firstly, getComptedStyle doesn't exist in earlier versions of IE. They instead use the currentStyle property. Thankfully it is absurdly easy to shim this:
if( typeof getComputedStyle == "undefined") getComputedStyle = function(elem) {return elem.currentStyle;};
Now that that's been solved, remove that null argument as it is completely redundant. Actually, I didn't even know getComputedStyle had a second argument, but that's just me.
Next, you can get the cursor property just by getting .cursor (or ['cursor']) instead of that .getPropertyCSSValue call (which again I have never heard of...). You can also drop the || "" since getComputedStyle will return an empty string if the cursor property has not been set.
You don't need to trim spaces, but switching to lowercase seems like a good idea just to be on the safe side.
... But then, immediately after toLowerCase(), you check THREE different capitalisations of the word? Really?
Additionally, you never define elm (which is where your actual problem is), and you should cache the value of elms.length.
The final code should look like:
if( typeof getComputedStyle == "undefined") getComputedStyle = function(elem) {return elem.currentStyle;};
var elms = document.getElementsByTagName("*"), l = elms.length, i;
for( i=0; i<l; i++) {
if( getComputedStyle(elms[i]).cursor.toLowerCase() === "pointer") {
elms[i].style.cursor = "wait";
}
}
If you want to be able to undo this, you will need to store an array of elements that you're modifying, loop through it and remove the style (.style.cursor = "";).

Javascript find child class

I have a table. When the item is dropped I need to apply padding to a single table cell. I have flagged that cell with a class. How do I select it?
droppedRow contains the table row that is has just been dropped.
If it was an id I would do droppedRow.getElementById('..'); Is there something similar for class names. Needs to support >= IE7
Thanks
Using vanilla JavaScript, you'll probably need to load up all of the element's by tag name and then locate it by evaluating each element's classname.
For example (the styles are just for example)...
var tableCells = document.getElementsByTagName('td');
for(var i = 0, l = tableCells.length; i < l; i++) {
if(tableCells[i].className === 'droppedRow') {
tableCells[i].style.padding = '1em';
}
}
If, on the other hand, you're using jQuery, then you should be able to use:
$('.droppedRow').css('padding', '1em');
Note however that in both of these examples, all cells that have the droppedRow class name will receive this styling (rather than just a single element).
If you're not using a library, I'd say stick with the vanilla variant of this functionality - libraries would be too much overhead just to condense this to a single line.
Maxym's answer also provides a solid implementation of getElementsByClassName for older browsers.
There exists getElementsByClassName but it is not supported in IE. Here is what you can do:
var element;
// for modern browsers
if(document.querySelector) {
element = droppedRow.querySelector('.yourClass');
}
else if(document.getElementsByClassName) { // for all others
element = droppedRow.getElementsByClassName('yourClass')[0];
}
else { // for IE7 and below
var tds = droppedRow.getElementsByTagName('td');
for(var i = tds.length; i--; ) {
if((" " + tds[i].className + " ").indexOf(" yourClass ") > -1) {
element = tds[i];
break;
}
}
}
Reference: querySelector, getElementsByClassName, getElementsByTagName
Clientside getElementsByClassName cross-browser implementation:
var getElementsByClassName = function(className, root, tagName) {
root = root || document.body;
if (Swell.Core.isString(root)) {
root = this.get(root);
}
// for native implementations
if (document.getElementsByClassName) {
return root.getElementsByClassName(className);
}
// at least try with querySelector (IE8 standards mode)
// about 5x quicker than below
if (root.querySelectorAll) {
tagName = tagName || '';
return root.querySelectorAll(tagName + '.' + className);
}
// and for others... IE7-, IE8 (quirks mode), Firefox 2-, Safari 3.1-, Opera 9-
var tagName = tagName || '*', _tags = root.getElementsByTagName(tagName), _nodeList = [];
for (var i = 0, _tag; _tag = _tags[i++];) {
if (hasClass(_tag, className)) {
_nodeList.push(_tag);
}
}
return _nodeList;
}
Some browsers support it natively (like FireFox), for other you need provide your own implementation to use; that function could help you; its performance should be good enough cause it relies on native functions, and only if there is no native implementation it will take all tags, iterate and select needed...
UPDATE: script relies on hasClass function, which can be implemented this way:
function hasClass(_tag,_clsName) {
return _tag.className.match(new RegExp('(\\s|^)'+ _clsName +'(\\s|$)'));
}
It sounds like your project is in need of some JQuery goodness or some Dojo if you need a more robust and full-fledged javascript framework. JQuery will easily allow you to run the scenario you have described using its selector engine.
If you are using a library, why not use:
JQuery - $("#droppedRow > .paddedCell")
Thats the dropped row by ID and the cell by class
Prototype - $$("#droppedRow > .paddedCell")

Get border value with getComputedStyle().getPropertyValue()? (Mozilla, FF)

In some browsers (namely, Firefox) the getComputedStyle().getPropertyValue() doesn't report anything for shorthand CSS, like border. Is there a non-specific-code way of getting these shorthand CSS values? I've considered making a whitelist of shorthand CSS and their respective longhand CSS values. But I realize doing that would be both a big pain and a non-forward-compatible design.
I'm wondering, what do you want to do with a string like border: 1px solid #000?
Say you want to reproduce an elems border in order to copy it copyStyle(el2, el, "border"):
// Copies a set of styles from one element to another.
function copyStyle(dest, source, shorthand) {
var computed = window.getComputedStyle(source, null);
for (var i = computed.length; i--;) {
var property = camelize(computed[i]);
if (property.indexOf(shorthand) > -1) {
console.log(property)
dest.style[property] = computed[property];
}
}
}
// prototype.js
function camelize(text) {
return text.replace(/-+(.)?/g, function (match, chr) {
return chr ? chr.toUpperCase() : '';
});
}
Comparing if two element's given set of styles matches can be done in the same manner. Other than that, I really can't see the use a string, which should be parsed if you want to compute anything with it.

Categories