Bogdan
Bogdan

Reputation: 713

JavaScript insert button before link, not after

I have the following example of code where I insert a button after the page is loaded, and I would like for that button to go inside of that div, but after that link is it posible (link to jsFiddle)?

HTML

<div class="someclass" id="someid">
    <a href="#" class="">Text Here</a>
</div>

JavaScript

(function(root) {
    function bindUIActions() {
        menuElements();
    }
    function menuElements() {
        var menuElements = document.getElementById("someid");
        menuElements.insertAdjacentHTML('afterBegin','<button type="menu-button" id="responsiveToggle" class="menu-button" aria-hidden="true"><i aria-hidden="true" class="icon-reorder"></i>Menu</button>');
    }
    root.NavigationWidget = {
        init: function() {
            bindUIActions();
        }
    };

})(this);
NavigationWidget.init();

Upvotes: 1

Views: 186

Answers (2)

adeneo
adeneo

Reputation: 318242

It seems like a lot of code, but the more proper way to do it would be:

var menuElements = document.getElementById("someid"),
    button       = document.createElement('button'),
    i            = document.createElement('i'),
    txt          = document.createTextNode('Menu');

button.type      = 'button';
button.id        = 'responsiveToggle';
button.className = 'menu-button';

i.className      = 'icon-reorder';

button.setAttribute('aria-hidden', 'true');
i.setAttribute('aria-hidden', 'true');

button.appendChild(i);
button.appendChild(txt);
menuElements.appendChild(button);

FIDDLE

Upvotes: 2

philwills
philwills

Reputation: 995

Use 'beforeend'

menuElements.insertAdjacentHTML('beforeend','<button type="menu-button" id="responsiveToggle" class="menu-button" aria-hidden="true"><i aria-hidden="true" class="icon-reorder"></i>Menu</button>');

https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML

Upvotes: 1

Related Questions