Failed to execute 'appendChild' in 'Node': new child is null

This strange mistake has been listening to me for half an hour. I am dynamically trying to apply a slider using only JavaScript. Any idea why this is happening to me? I could find other questions about SO, but could not understand the solution. I am new to JS and appreciate if anyone can explain things to me in the laity. Here is my code.

MARKUP

<!DOCTYPE html> <html> <head> <title>JS sample test page</title> <link rel="stylesheet" type="text/css" href="jquery.bxslider.css"> </head> <body> <div class="og-fullimg"></div> <script type="text/javascript" src="jquery-1.11.1.js"></script> <script type="text/javascript" src="jquery.bxslider.min.js"></script> <script type="text/javascript" src="main.js"></script> </body> </html> 

JAVASCRIPT

 // code for thumbnail slider begins (function() { var ogImg = document.getElementsByClassName("og-fullimg"); alert(ogImg.length); var bxSlider = document.createElement("ul"); //created ul bxSlider.setAttribute("class", "bxslider"); // gave a class name bxslider. for (i = 1; i < 4; i++) { var itemsList = document.createElement("li"); var linkImages = document.createElement("img"); linkImages.src = "images/bid_" + i + ".jpg"; itemsList.appendChild(linkImages); bxSlider.appendChild(itemsList); } ogImg[0].appendChild(bxSlider); document.body.appendChild(ogImg); //append everything to the body. //call the slider. $(document).ready(function() { $('.bxslider').bxSlider({ auto: true, pager: false, adaptiveHeight: true, slideWidth: 550 }); }); }()); // code for thumbnail slider ends. 

Thanks in advance.

+6
source share
1 answer

A few questions here:

  • document.body.appendChild(ogImg); just wrong. ogImg is a nodeList . You cannot directly add a nodeList to the body. And this is already in the DOM (you just got it with document.getElementsByClassName("og-fullimg");

  • You use $(document).ready() to wait for a call to .bxSlider (), but DO NOT use it to call document.getElementsByClassName() . I assume your code will run too fast. If so, then just put all your code inside the .ready() handler.

  • You use a very strange combination of plain javascript and jQuery when switching plain javascript to jQuery to make your code smaller and more consistent. If you have jQuery, you can also use it for what it's good (which is a selector and operations on collections - by the way).

Here is what I suggest:

 //create and initialize the slider. $(document).ready(function() { var bxSlider = $("<ul class='bxslider'></ul>"), img; for (var i = 1; i < 4; i++) { img = new Image(); img.src = "images/bid_" + i + ".jpg"; $("<li>").append(img).appendTo(bxSlider); } bxSlider.appendTo(".og-fullimg"); bxSlider.bxSlider({ auto: true, pager: false, adaptiveHeight: true, slideWidth: 550 }); }); 
+7
source

Source: https://habr.com/ru/post/973586/


All Articles