简体   繁体   中英

How to fix undefined divs in javascript?

For Example I Type

var x1 = document.getElementsByClassName('js-ticket-count');

undefined & HtmlCollection !

x1 = document.getElementsByClassName('js-ticket-count')[0];

it return as undefined? why?

Html Code:

<div class='js-ticket-count'>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<div>
**More Html Stuff Here**
 </div>
                    </div>

Try putting your JS inside an onload listener. Otherwise it's likely your JS is running before the elements have loaded into the DOM.

window.onload = function(){
    alert(document.getElementsByClassName('js-ticket-count')[0]);
}

The HtmlCollection you're seeing is basically an array of elements, as there may be multiple elements with a certain class name. You're returning the first element with [0] .

  • you can use DOMContentLoaded event to make sure that document is loaded like this:
document.addEventListener("DOMContentLoaded", function(){
    var x1 = document.getElementsByClassName('js-ticket-count');
        x1 = document.getElementsByClassName('js-ticket-count')[0];
    console.log(x1)
})
  • you can also use load event on window object like this:
window.addEventListener("load", function(){
    var x1 = document.getElementsByClassName('js-ticket-count');
        x1 = document.getElementsByClassName('js-ticket-count')[0];
    console.log(x1)
})
  • also make sure that your script tag on before of body tag close to make sure that the every element is loaded.

If in case you are using the external JS file then maybe add it at the end of the body element. So your JS file will load after all the HTML elements have been loaded. In this way, JS can read the HTML element. Something like this:

<body>
    <div class='js-ticket-count'>
    <p id='style-1'>test<p>
    <p id='style-1'>test<p>
    <p id='style-1'>test<p>
    <p id='style-1'>test<p>
    <p id='style-1'>test<p>
    <div>
    **More Html Stuff Here**
     </div></div>
     
     <script srs="externalJSlink.js"></script>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM