var elem = $('#'+ id)[0]; var children = elem.children[0].children; var duration = children[1].innerText; 

Gives an error message:

Cannot read property 'children' of undefined

(on the 2nd line). But if I try to bring the children variable to the console, I will get back not undefined , but what I need is the descendants of the elem element. If I try to output children[1].innerText , I get what I need. Why then do i get an error? If you display console.log(children.toString()); , then [object HTMLCollection] is displayed. Here is the html code (which is dynamically loaded):

 <div class="song local" id="pc-9" url="some path"> <ul> <li class="name">Bob Dylan - Blowin' in the wind</li> <li class="duration">2:49</li> </ul> </div> 
  • "on the 2nd line" and "output ... the variable children " - contradict each other. If an error occurs in the 2nd line, the children variable will not be assigned. Try to reformulate the question. Markup html will also be useful. - Igor
  • If you work with dynamically created elements, then this is possible, just a non-initialized element appears on the page and js does not see it. - Boris Runs
  • but on the very next line console.log (children); gives out not undefined - Vlad Furman
  • here is the html markup: <div class = "song" id = "pc-9" url = "Bob Dylan - Blowin 'in the wind.mp3"> <ul> <li class = "name"> Bob Dylan - Blowin' in the wind </ li> <li class = "duration"> 2:49 </ li> </ ul> </ div> - Vlad Furman
  • @JohnBlumen please remember that comments are not intended to display your code. Transfer your code to the question text. - Alex

1 answer 1

Most likely, your code will work before the entire DOM page is loaded . When you enter something into the console, it works out, since the page is loaded. To be sure that this does not happen, wrap your code in $(document).ready() :

 $(document).ready(function() { var elem = $('#'+ id)[0]; var children = elem.children[0].children; var duration = children[1].innerText; }); 

Then you can be sure that the code is executed after loading the entire DOM page.

  • No, the code is wrapped in $ (document) .ready (), moreover, it happens much later than the page load - Vlad Furman
  • @JohnBlumen Is the variable still not assigned anywhere? - teo van kot
  • No, nowhere. But if you bring children.toString () into the console, it gives [object HTMLCollection], maybe that's the problem - Vlad Furman
  • one
    @JohnBlumen Do you always have this structure? WMS easier to rewrite the selector than here to suffer? - teo van kot