javascript add element before div code example

Example 1: javascript add div before element

var my_elem = document.getElementById('my_id');

var span = document.createElement('span');
    span.innerHTML = '*';
    span.className = 'asterisk';

my_elem.parentNode.insertBefore(span, my_elem);

Example 2: js insertbefore

// The Node.insertBefore() method inserts a node before a
// reference node as a child of a specified parent node.
let insertedNode = parentNode.insertBefore(newNode, referenceNode)

Example 3: javascript insert html before element

// add without creating a new element
document.getElementById('my_id')
.insertAdjacentHTML('beforebegin', 'your_html_code');