Reputation: 3490
I created a button of Id tag.When I clicked it, I want it to display a div with z-index 1.But why z-index can't be accessed through javascript:
var tag = document.getElementById('tag');
tag.onclick = function(){
var tag_div = document.createElement("div");
tag_div.id = "wow";
document.body.appendChild(tag_div);
tag_div.style.border = "1px solid black";
tag_div.style.position = "absolute";
tag_div.style.top = "200px";
tag_div.style.left = "70px";
tag_div.style.z-index = 1;
return false;
}
Upvotes: 0
Views: 568
Reputation: 168695
Your code:
tag_div.style.z-index = 1;
This is invalid Javascript code because of the hyphen -- Javascript sees the hyphen as a minus sign, and interprets it as a subtraction, which will fail.
If you need to access an object property whose name contains a hyphen, you must use the following syntax instead:
obj['property-name']
This is a general rule for all JS properties.
However specifically for CSS properties, they are generally exposed to Javascript using camel-case names rather than hyphenated names (camel-case means no hyphens, but capitalised letters for new words where a hyphen would have been), so the following should work:
tag_div.style.zIndex = 1;
Hope that helps.
Upvotes: 2
Reputation: 55643
All CSS rules that have dashes (background-image, z-index, margin-top) can be accessed through JavaScript using camelCase property values like:
div.style.backgroundImage
div.style.zIndex
div.style.marginTop
Upvotes: 1
Reputation: 101614
As a general rule of thumb, CSS styles that include hyphens (for the purpose of javascript access) are converted to camelCase. That is to say, z-index
becomes zIndex
just like background-color
becomes backgroundColor
.
See JavaScript and CSS:
In JavaScript,
backgroundColor
corresponds to the CSS propertybackground-color
. JavaScript does not allow hyphens in names, so "camelCase" is used instead.
Upvotes: 4
Reputation: 339826
CSS rules in stylesheets use hyphens, CSS properties use camel case, so you need .zIndex
Upvotes: 11