0
votes
var aa = 0;
var arr = new Array("one", "two", "three");
var arr1 = new Array("four", "five", "six");

function cl(me) {
    me.clicked = !me.clicked;
    var id = me.id;
    if (me.clicked) {
        if (id == 1000) aa = arr;
        if (id == "one" || id == "two" || id == "three") aa = arr1;
        var s = document.getElementById("sample");
        var d = document.createElement("div");
        d.id = me.id + 1;
        s.appendChild(d);
        for (i = 0; i < aa.length; i++) {
            var l = document.createElement("label");
            l.innerHTML = aa[i];
            l.id = aa[i];
            l.onclick = function (){cl(this)};
            d.appendChild(l);
        }
    } else {
        var child = document.getElementById(me.id + 1);
        var parent = document.getElementById("sample");
        parent.removeChild(child);
    }
}

Markup:

<label id="1000" onclick="cl(this)">click</label><br><div id="sample"></div>

When the label "click" is clicked, three labels "one" "two" "three" are generated successfully.

When I click label "one" labels "four" "five" "six" are generated successfully.

When I again click label "one" "three four five" labels are removed.

But the problem is when I click label "click" and then label "one" .. now when i click "one" again the label "one two three" is alone removed but not "four five six".

1
Can you give a more realistic example? because with this code it looks more like a competition to see who can decipher the code. I'm guessing the idea is to have like a tree structure where it opens when you close the top one it closes all below it? - user203715
ya how to make it like a tree structure............. - thuk
Your code is tangled. Do it more obvious. We can help to resolve this local problem, but there will be many problems in your development. - sergzach
Separate logic from document.getElementById - sergzach
@sergzach: You mean: don't use ids of DOM elements to store keys to vital parts of the code. - Marcel Korpel

1 Answers

0
votes

HTML label elements do not have a clicked attribute so it's not a good idea to give them a clicked property.

Labels are meant for form controls that don't have a label or caption, such as radio buttons and checkboxes. A more appropriate element here would be a button (either a button or input type button element).

Id attributes must start with a letter, they can't be all numbers.

Browsers will tolerate all of the above, however it's not a good idea to ignore specifications because a browser may be released that adheres to the specification in ways your code doesn't.

I think your issue is that the labels created by one look just like the ones created by four. If you remove four by clicking on one, you can't remove the labels it created until you create it again.

Use an element inspector to see what's happening.