shinyMao shinyMao - 3 months ago 16
jQuery Question

"js Uncaught TypeError: Cannot set property 'zIndex' of undefined"

In order to change z-index of a picture after a action,I write the following code in js.

$("id").click(function{

document.getElementsByClassName.style.zIndex = 2;
});


however,it show the error like


js Uncaught TypeError: Cannot set property 'zIndex' of undefined


is there anyone face the same problem and has solved it? THX

Answer

First getElementsByClassName requires an argument passed to it, to specify which class name the elements should contain, you want to receive.

Just pick the first one of the returned array and operate on that value, be sure to check if the returned array contains any elements:

$("id").click(function{
 var elements = document.getElementsByClassName('some-class-name');
 if (elements.length > 0) {
  elements[0].style.zIndex = 2;
 }

});

But I really would suggest you to use jQuery to ensure cross browser compatibility.

$("id").click(function{
 var elements = $('.some-class-name');
 if (elements.length > 0) {
  elements.first().css({ 'z-index' : 2 });
 }

});

EDIT: Because you said, you want to change the zIndex of ONE image object, I use first() in jQuery and [0] in vanilla JS to get operate on the first element, only. But just use an unique id attribute as identifier to query only one element in this case.

Comments