dramasea
dramasea

Reputation: 3490

Why z-index in css can't be accessed through javascript

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

Answers (6)

Spudley
Spudley

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

Adam Jenkins
Adam Jenkins

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

Brad Christie
Brad Christie

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 property background-color. JavaScript does not allow hyphens in names, so "camelCase" is used instead.

Upvotes: 4

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

It is:

tag_div.style.zIndex = 1;

Upvotes: 0

gvee
gvee

Reputation: 17161

Try this:

tag_div.style.zIndex = 1;

Upvotes: 2

Alnitak
Alnitak

Reputation: 339826

CSS rules in stylesheets use hyphens, CSS properties use camel case, so you need .zIndex

Upvotes: 11

Related Questions