amarinediary
amarinediary

Reputation: 5441

Append an element before a element wrapping a body innerHTML, vanilla Js

I'm trying to insert an element before an element wrapping over the body but getting the following

Uncaught TypeError: Cannot read property 'insertBefore' of null

document.querySelector( 'body' ).innerHTML = '<div id="boat">' + document.querySelector( 'body' ).innerHTML  + '</div>';

var sailor = document.createElement( 'aside' );
sailor.setAttribute( 'id', 'sailor' );
sailor.parentNode.insertBefore( document.getElementById( 'boat' ), sailor );

Any ideas on how to realize the following structure?

<body>
  <aside id="sailor"></aside>
  <div id="boat">
    <!-- 
    rest of the content -->
  </div>
</body>

Upvotes: 0

Views: 586

Answers (3)

Samuel Anyanwu
Samuel Anyanwu

Reputation: 315

sailor.parentNode.insertBefore( document.getElementById( 'boat' ), sailor );

Here you're trying to get the parent node of an element that does not exist on the DOM, so there is no parent hence null.

Also that isn't the correct way to use the insertBefore method. From the MDN web documentation I see

let insertedNode = parentNode.insertBefore(newNode, referenceNode)

The div with id boat is the reference node, the sailor element is the new node and the body is the parent node. With that we can rewrite the code as

document.querySelector( 'body' ).innerHTML = '<div id="boat">' + document.querySelector( 'body' ).innerHTML  + 'test </div>';

var sailor = document.createElement( 'aside' );
console.log(sailor);
sailor.setAttribute( 'id', 'sailor' );
document.body.insertBefore( sailor, document.getElementById( 'boat' ) )

Upvotes: 0

Phillip Rekhotho
Phillip Rekhotho

Reputation: 91

sailor is not added into the DOM so it doesn't have a parent.. you need to add it into the DOM first before you can access its parent element

Upvotes: 0

Musa
Musa

Reputation: 97672

The sailor node has no parent, it is the boat element you have to ge the parent of. Also, the node you are inserting is the first parameter.

var sailor = document.createElement( 'aside' );
sailor.setAttribute( 'id', 'sailor' );
var boat = document.getElementById( 'boat' );
boat.parentNode.insertBefore( sailor, boat );

Upvotes: 4

Related Questions