Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add elements to different <li>

I have this code where there is a question and many options.
I have an unordered list ul and I am trying to all in that list many li where each one will contain a option name and a checkbox.

My code for the moment add the li but it add the checkbox and the name under it and not in it.

It looks something like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<ul>
<li class="optionName"></li>
<label for="checkbox00">Option 0</label>
<input type="checkbox" id="checkbox00">
<li class="optionName"></li>
<label for="checkbox01">Option 1</label>
<input type="checkbox" id="checkbox01">
</ul>

And I want it to look like this:

<ul>
<li class="optionName" <label for="checkbox00">Option 0</label> <input type="checkbox" id="checkbox00">></li>
<li class="optionName" <label for="checkbox01">Option 1</label> <input type="checkbox" id="checkbox01">></li>
</ul>

My code where I am adding the html looks like this:

        var option = document.createElement('li');
        var checkbox = document.createElement('input');
        var label = document.createElement('label')
        var checkBoxId = "checkbox" + "" + questionNumber + subquestionNumber;
        checkbox.type = "checkbox";
        checkbox.id = checkBoxId;
        option.className = "optionName";
        label.htmlFor = checkBoxId;
        checkBoxId.htmlFor = option;
        label.appendChild(document.createTextNode('Option ' + subquestionNumber));
        q.appendChild(option)
        q.appendChild(label);
        q.appendChild(checkbox);

>Solution :

You should call appendChild on option instead of q

var option = document.createElement('li');
        var checkbox = document.createElement('input');
        var label = document.createElement('label')
        var checkBoxId = "checkbox" + "" + questionNumber + subquestionNumber;
        checkbox.type = "checkbox";
        checkbox.id = checkBoxId;
        option.className = "optionName";
        label.htmlFor = checkBoxId;
        checkBoxId.htmlFor = option;
        label.appendChild(document.createTextNode('Option ' + subquestionNumber));
        option.appendChild(label); //add `label` to `li`
        option.appendChild(checkbox); //add `checkbox` to `li`
        q.appendChild(option)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading