最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.getElementsByClassName() not working - Stack Overflow

programmeradmin6浏览0评论

I am trying to create a fallback in the absence of jQuery, as I have a div with the class 'container' and a style display: none

I use jquery to fadeIn() this div, to create a fade effect on page (re)load (I know there are better ways to do this, however I would like to do it this way.)

However, in case of lack of jQuery (!window.jQuery) I am creating a JavaScript solution to make my page visible.

But my attempts at using document.getElementsByClassName() have so far failed, and always return 'undefined'
I understand I can loop through them, but this seems a little OTT for targeting one element.

None of the following attempts have worked:

  1. All together, with [0] node selection:

    document.getElementsByClassName("container")[0].style.display = "block";
    
  2. All together, without [0], as I want to style all (1) of the elements with the class name "container":

document.getElementsByClassName("container").style.display = "block";

  1. Set as a variable, then take the [0] node and style it*

    var container = document.getElementsByClassName("container");
    container[0].style.display = "block";
    

N.B. I know there are many questions of this nature on SO, however mine is different as there is only one element with the class am trying to select, so I would rather not loop through them.

The console throws the following error message:

Uncaught TypeError: Cannot read property 'style' of undefined(anonymous function)

And also when I console.log them in each instance, it says they're undefined

I am trying to create a fallback in the absence of jQuery, as I have a div with the class 'container' and a style display: none

I use jquery to fadeIn() this div, to create a fade effect on page (re)load (I know there are better ways to do this, however I would like to do it this way.)

However, in case of lack of jQuery (!window.jQuery) I am creating a JavaScript solution to make my page visible.

But my attempts at using document.getElementsByClassName() have so far failed, and always return 'undefined'
I understand I can loop through them, but this seems a little OTT for targeting one element.

None of the following attempts have worked:

  1. All together, with [0] node selection:

    document.getElementsByClassName("container")[0].style.display = "block";
    
  2. All together, without [0], as I want to style all (1) of the elements with the class name "container":

document.getElementsByClassName("container").style.display = "block";

  1. Set as a variable, then take the [0] node and style it*

    var container = document.getElementsByClassName("container");
    container[0].style.display = "block";
    

N.B. I know there are many questions of this nature on SO, however mine is different as there is only one element with the class am trying to select, so I would rather not loop through them.

The console throws the following error message:

Uncaught TypeError: Cannot read property 'style' of undefined(anonymous function)

And also when I console.log them in each instance, it says they're undefined

Share Improve this question edited Jul 10, 2015 at 17:06 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Jul 10, 2015 at 16:59 joe_youngjoe_young 4,1252 gold badges29 silver badges38 bronze badges 9
  • 3 Have you checked the console for errors? – Rory McCrossan Commented Jul 10, 2015 at 17:01
  • Yeah, it throws Uncaught TypeError: Cannot read property 'style' of undefined(anonymous function) @RoryMcCrossan – joe_young Commented Jul 10, 2015 at 17:01
  • 1 The first example you have (which is the correct method) works fine: jsfiddle/b48prmv4 – Rory McCrossan Commented Jul 10, 2015 at 17:02
  • Can you post a broken fiddle? As @RoryMcCrossan mentioned, this works fine. – Tom Commented Jul 10, 2015 at 17:03
  • 2 Are you running it after the DOM is ready? May be you are running the code while the ".container" isn't present yet. Because the code document.getElementsByClassName("class")[index] is the correct one. – Mindastic Commented Jul 10, 2015 at 17:05
 |  Show 4 more ments

3 Answers 3

Reset to default 5

You are most likely running that code before the elements of class container exist.

Your jQuery probably works because you have it in a $(document).ready callback ($( function( ) { ... is a mon way to do this).

Either add your non jQuery code to a window.onload event handler, or simply move your script to lower in your HTML than the elements are that you want it to select. Right before the closing </body> is a mon place for scripts that require the whole document to be available in the DOM.

Try wrapping your code in an onload function:

window.onload=function(){
    // Your JS code goes here
}

Alternatively, put your JS code at the very bottom of your HTML body.

<html>
    <head>
        <!-- Start of head section -->
        <!-- Your HTML head content goes here -->
        <!-- End of head section -->
    </head>
    <body>
        <!-- Start of body section -->
        <!-- Your HTML body content goes here -->
        <!-- End of body section -->
        <script type='text/javascript'>
            // Your JS code goes here
        </script>
    </body>
</html>

You can use document.querySelector(".container") which will automatically select the first item in the node list for you.

发布评论

评论列表(0)

  1. 暂无评论