Glyphicon on dynamic button

10,241

I hope I understand your problem correctly. You want to add a button via javascript and then add an icon to that button.

This example adds a button to the DOM and when you click the button; it appends the icon to itself.

JSFiddle: http://jsfiddle.net/e9f2M/1/

function createRemoveIcon(){
    var button = document.createElement("button");
    button.setAttribute('class', 'btn btn-default');
    button.innerHTML = 'click me';
    button.onclick = function(){ 
        var icon = document.createElement("span");

        icon.className ="glyphicon glyphicon-remove-circle";
        this.appendChild(icon);
    }
    document.getElementById("container").appendChild(button);
}
Share:
10,241
jaredramirez
Author by

jaredramirez

Working in Haskell, Elm, and ReasonML.

Updated on June 09, 2022

Comments

  • jaredramirez
    jaredramirez almost 2 years

    I'm trying to add a glyphicon to my dynamically created button in my javascript file. I can add it in the actual html file but I can't figure out how to add it from javascript

    function createRemoveIcon(){
        var icon = document.createElement("span");
    
        icon.className ="glyphicon glyphicon-remove-circle";
    
        alert("test" + icon);
    }
    

    Or this is how I was originally trying to create it

    function createRemoveRowButton(attendeeArrayIndex) {
        var removeIcon = document.getElementById("removeIcon");
    
        var removeRowButton = document.createElement("BUTTON");
        var icon = document.createTextNode(removeIcon);
        removeRowButton.appendChild(icon);
        removeRowButton.onclick = function() {
            deleteRow(attendeeArrayIndex);
        };
        return removeRowButton;
    }
    
  • Markus W Mahlberg
    Markus W Mahlberg about 9 years
    Mind to explain your solution a bit?