1
<label id="1" >a</label><label id="2" > b </label>

I have two labels created. When a label is clicked, I create a div element within that I displayed. Now I need to remove the created div element if the label is again clicked.

if (click == 1) {
    var prevWin = document.createElement("div");
    prevWin.id = 1;
    prevWin.innerHTML = outMsg;
    document.body.appendChild(prevWin);
} else {
    var prevWin = document.body.getElementsById(1);
    document.body.removeChild(prevWin);
}

When a label is clicked the div element is created successfully. But when it is clicked again, the div element is not removed.

1 Answer 1

3
function labelOnClick () {
    var divs = this.getElementsByTagName("div");

    if (divs.length) {
        divs[0].parentNode.removeChild(divs[0]);
    } else {
        var div = document.createElement("div");
        div.innerHTML = outMsg;

        this.appendChild(div);
    }
}

ids have got to be unique throughout the DOM; in your example, it looks like you'll have the label and the div with the same id. You could easily append a string to the div id, if you want it to have an id (div.id = this.id + "_div").

My example wont work if you have more than one div in your label; in which case the ID approach would be best (or use a selector library).

Id's could be approached as follows:

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 = outMsg;
        div.id = makeDivId(this.id);

        this.appendChild(div);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks.....but what to do. if we want to have more than one div element. i the above example.
You can have multiple div elements, but only one per label. If you need multiple per label, you could apply a className to the divs, and filter them that way. If you can guarantee that all div descendants of the label will need to be removed, then just iterate over the array in the first example, calling div[i].parentNode.remove(div[i]) on all of them.
Alternately, you could use unique id's on all the divs; div_1, div_2, div_3, and remove them all manually. Finally, you could put all the divs in a single child (another div?) and then iterate over the childNodes of the label, and remove that element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.