0

I am selecting some elements using jQuery and applying CSS like this...

$(".items div").not(".active").css({"color":"green","background":"red","z-index:":"-9"});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="items">
  <div>Item 1</div>
  <div class="active">Item 2</div>
  <div>Item 3</div>
  <div>Item 4</div>
  <div>Item 5</div>
</div>

The background and the color both work, but the z-index is not being applied.

Where am I going wrong?

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • 5
    `z-index` is not applied to elements without a `position`. See [Why does z-index not work?](https://stackoverflow.com/q/9191803/215552) – Heretic Monkey Jul 24 '19 at 19:25
  • Elements don't necessarily accept the `z-index` attribute. There are several ways you can cause them to. The simplest one is probably to add a `position` attribute with a value other than `"static"`. (See https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context for a thorough explanation.) – Cat Jul 24 '19 at 19:28
  • what are you expecting to happen with z-index? – epascarello Jul 24 '19 at 19:31
  • You have multiple typos in your jQuery – j08691 Jul 24 '19 at 19:42

2 Answers2

2

If you don't style the element with the position property (relative, absolute, fixed), the element will remain in the normal document flow as a block or inline element. Elements in the normal document flow can't be layered with z-index.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
-1

You have an extra colon in your jQuery when setting z-index.

Should be

$(".items div").not(".active").css({"color":"green","background":"red","z-index":"-9"});
Anders L
  • 67
  • 4
  • 1
    Have you tried this and found it is now working? – Heretic Monkey Jul 24 '19 at 19:34
  • 1
    It applies the z-index properties to the DOM, whereas the original statement wouldn't because the colon caused jQuery to not recognize it as the property. The effect of z-index on these elements is not in the scope of the original question if that's what you're asking. – Anders L Jul 24 '19 at 19:39
  • 3
    Note that you can (when a question is open) click the Copy Snippet to Answer button under the snippet, which would then allow you to show your fix in action. That said, typos are a specific type of problem that is off-topic on Stack Overflow, since it is unlikely to help anyone other than the original poster, so we usually close them for that reason. A couple of things to keep in mind. – Heretic Monkey Jul 24 '19 at 19:42