Javascript DOM how to hide out of place checkbox

Viewed 82

I have a Div in which I dynamically create new labels. These labels consist of a span with unique ID for each, some text inputted by the user and most importantly a checkbox inside of the label. The checkbox serves for the user to select or deselect the created span. All of this works but for some reason the checkbox pops out of the span it should be in from my understanding (since the span is checkable) and appears a line above the span which creates gaps between my labels like so:

enter image description here

When I try to click it nothing happens. And the weirdest thing is that the span checkbox works. When I inspect the code I see this, so I know the checkbox is actually not inside the span:

enter image description here

Code I'm using to do this:

let wrapLabel = document.createElement("label") let inCheckBox = document.createElement("input")

    let x = document.createElement("span")
    let t = document.createTextNode(submission)

    let unique_id = uuidv4()

    inCheckBox.type = "checkbox"
    inCheckBox.name = unique_id 

    x.className = "item item-layer"
    x.id = unique_id 

    x.appendChild(t)
    wrapLabel.appendChild(inCheckBox) // replace this by x.appendChild(inCheckBox)
    wrapLabel.appendChild(x)
    wrapLabel.className = "wrapLabel"

    document.querySelector('.LayerList').appendChild(wrapLabel); 

The problem is that when I try to do something like x.appendChild(inCheckBox) the span is no longer checkable.... Ideally I'm just looking to use my current code and hide the gap from checkbox above the span if possible

1 Answers

I tested the same thing just to understand better. I suggest you to create only span tags and add/remove the class selected based on your needs. I mean, if you click on a span it will add the class selected like this:
<span class="item item-layer selected">layer 1</span> If you don't want that class, just click on the span again. You can do the work with javascript:

document.querySelectorAll('.item-layer').forEach(item => {
    item.addEventListener('click', () => {
            if(item.classList.contains('selected'))
                item.classList.remove('selected');
            else
                item.classList.add('selected');
        });
    });

The css will be something like this:

.selected {
   border-color: green;
}

When it's not selected you put red.
Then you can querySelectorAll every span that has the class selected and do whatever you need.

Related