html - JavaScript script not running? - Stack Overflow

The idea of this code is to show an unordered list of HTML elements, but for some reason, it seems like

The idea of this code is to show an unordered list of HTML elements, but for some reason, it seems like it doesn't work.

I'm using Sublime Text to write the script and the HTML code. I've tried to execute the script through Chrome developers console, and it didn't work either.

// 1) Crear una lista desordenada con 10 elementos dentro usando un bucle for.
//    Tener en cuenta que solo se le puede hacer un único appendChild al ul creado, 
//    asi minimizamos el tiempo de modificaciones en el DOM.

var list = document.createElement('ul');
var elements = document.createDocumentFragment();

for (var i = 0; i < 10; i++) {
  let element = document.createElement('li');
  element.innerText = "Elemento " + i;
  elements.appendChild(element);
}

list.appendChild(elements);
document.body.appendChild(list);

The idea of this code is to show an unordered list of HTML elements, but for some reason, it seems like it doesn't work.

I'm using Sublime Text to write the script and the HTML code. I've tried to execute the script through Chrome developers console, and it didn't work either.

// 1) Crear una lista desordenada con 10 elementos dentro usando un bucle for.
//    Tener en cuenta que solo se le puede hacer un único appendChild al ul creado, 
//    asi minimizamos el tiempo de modificaciones en el DOM.

var list = document.createElement('ul');
var elements = document.createDocumentFragment();

for (var i = 0; i < 10; i++) {
  let element = document.createElement('li');
  element.innerText = "Elemento " + i;
  elements.appendChild(element);
}

list.appendChild(elements);
document.body.appendChild(list);
Share Improve this question edited Jul 19, 2018 at 12:35 Rick 4,1249 gold badges27 silver badges37 bronze badges asked Jul 19, 2018 at 0:38 esteban druettaesteban druetta 751 gold badge1 silver badge10 bronze badges 3
  • 3 Are there any errors in the console? – Smokey Dawson Commented Jul 19, 2018 at 0:43
  • There's nothing wrong with what you've written, it should work fine. There's no way for us to tell why it isn't working for you. – Barmar Commented Jul 19, 2018 at 0:48
  • We're gonna need more code. Perhaps provide your HTML so we can see whether the script tag is in the correct place. – gotnull Commented Jul 19, 2018 at 0:53
Add a ment  | 

2 Answers 2

Reset to default 0

It works when you do the same thing via a function after DOM is loaded. It gives this error in the console (F12 in Chrome) otherwise -

Uncaught TypeError: Cannot read property 'appendChild' of null

This is perhaps because of the unavailability of DOM during initial execution of the script and the hence the node is not available for the 'appendChild' function call.

Check this out, I am calling the same code via a function which works as expected -

<html>
<script> 
    //var list = document.getElementById('test');
    //var elements = document.createDocumentFragment();
    console.log(list);
    for (var i = 0 ; i < 10 ; i++){
       /* let element = document.createElement('li');

        element.innerText = "Elemento " + i;
        console.log(i);*/

        var node = document.createElement("LI");                 // Create a <li> node
        var textnode = document.createTextNode("Water");         // Create a text node
        node.appendChild(textnode);                              // Append the text to <li>
        document.getElementById('myList').appendChild(node);
    }

    //list.appendChild(elements);

    //document.appendChild(list);
     function myFunction() {
            var node = document.createElement("LI");
            var textnode = document.createTextNode("Water");
            node.appendChild(textnode);
            document.getElementById("myList").appendChild(node);
        }

</script>
<body>
    <button onclick="myFunction()">Try it</button>
    <ul id="myList">
      <li>Coffee</li>
      <li>Tea</li>
  </ul>
</body>
</html>

Hope this helps!!

Ensure your script tag is in the correct place.

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

<!-- index.html -->
<html>
    <head>
        <title>Your Page</title>
        <script type="text/javascript">
           // javascript goes here
        </script>
    </head>
    <body>
        <div>Your body goes here.</div>
    </body>
</html>

var list = document.createElement('ul');
var elements = document.createDocumentFragment();

for (var i = 0 ; i < 10 ; i++) {
    let element = document.createElement('li');
    element.innerText = "Elemento " + i;
    elements.appendChild(element);
}

list.appendChild(elements);
document.body.appendChild(list);

It's working fine on our end.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745460542a4628690.html

相关推荐

  • html - JavaScript script not running? - Stack Overflow

    The idea of this code is to show an unordered list of HTML elements, but for some reason, it seems like

    7小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信