Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and removing <div> element in Javascript

function labelOnClick () {
    function makeDivId(id) {
        return id + "_div";
    };

    var div = this.getElementById(makeDivId(this.id));

    if (div) {
        div.parentNode.removeChild(div);
    } else {
        div = document.createElement("div");
        div.innerHTML = "welcome";
        div.id = makeDivId(this.id);

        this.appendChild(div);
    }
}




<label id="1" onclick="labelOnClick()" > BROWSER </label>
<label id="2" onclick="labelOnClick()"> GAMING CONSOLE </label>

In the above example, I'm trying to create a div element when a label is clicked and remove the created div element when the label is clicked again, but it's not working.

like image 418
thuk Avatar asked Dec 19 '25 22:12

thuk


1 Answers

You have several problems in your code:

  • When assigning event handlers inline (label onclick="...") inside the event handler function this will point to the global object (window). You can pass this as an argument to the function.

  • Certain browsers will fail when assigning the result of getElementById() to a variable if no element is found (someone correct me if I'm wrong).

Something like this would work:

<script>
function labelOnClick (me) {
    var makeDivId=function (id) {
        return id + "_div";
    };
    var div;

    if (document.getElementById(makeDivId(me.id))) {
        div=document.getElementById(makeDivId(me.id));
        div.parentNode.removeChild(div);
    } else {
        div = document.createElement("div");
        div.innerHTML = "welcome";
        div.id = makeDivId(me.id);

        me.appendChild(div);
    }
}
</script>

<label id="1" onclick="labelOnClick(this)" > BROWSER </label>
<label id="2" onclick="labelOnClick(this)"> GAMING CONSOLE </label>

jsFiddle Demo

like image 156
kapa Avatar answered Dec 22 '25 14:12

kapa