Search code examples
javascriptnodelist

How do I divide bodycontent in two halves and insert html in the middle using Pure Javascript


I've done it with jQuery, but need to do it with PURE JS.

jQuery example:

$(document).ready(function() {
  var bodyContent = Math.floor($('#content').children().length);
  var bodyContentDividedInTwo = Math.floor(bodyContent / 2);


  $('#content').children(':eq('+bodyContentDividedInTwodedInHalf+')').after(`widget goes here`);
});

This is where I'm stuck with my PURE JS example:

 var fullBodyContent = document.querySelector('#contentBody');
 var bodyContentSplitInHalf = fullBodyContent.childElementCount / 2;

 bodyContentSplitInHalf.insertAdjacentHTML('afterbegin', '<h1>Yeeeeeeesssss!</h1>');

Then I get the obvious error of it not being a function. Because its a nodelist.

Please help, I know this is an easy one. But for some reason I always struggle to figure this out.


Solution

  • Is this what you're after?

    const index = Math.floor(fullBodyContent.childElementCount / 2);
    const bodyContentSplitInHalf = fullBodyContent.children[index];