0

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>

3 Answers 3

4

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 );
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, on point. Hard to switch back from jQ to jS.
0

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

Comments

0

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' ) )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.