简体   繁体   中英

Javascript: Adding and removing elements to dom

I am trying to dynamically add new elements to my html. But i am currently stuck on the "second level". It starts with a single div where new elements will get stored at:

<div id="inputquestions"></div>                   

When I click a button, new elements will get added to the div via a javascript function which looks something like this

function addQuestion() {
        var div = document.createElement('div');

        questionID++; // increment questionID to get a unique ID for the new element

        div.className = 'newQuestion';

        div.id = 'newQuestionID';

        div.innerHTML =
            "<div class='input-group'>" +
            "<input id='question-" + questionID + "' class='form-control' name='questionbox' type='text' placeholder='New Question'/>" +
            "<button class='btn btn-secondary' onclick='removeQuestion(this.parentNode)' type='button'>Remove</button>" +
            "</div>" +
            "<div class='btn-group' role='group' aria-label='Basic example'>" +
            "<button class='btn btn-secondary' onclick='addRadioButton()' type='button'>+ Radiobutton</button>" +             
            "</div>";

        document.getElementById('inputquestions').appendChild(div);
    }

This will create multiple divs inside the first div and I now want each div to create new divs for them individually but can't figure out how to do it. How does my function addRadioButton() have to look like in order to make the new divs appear inside the div I pressed the button at?

In your function addRadioButton() you can look at event.target.parentElement to get the <div> that contains the <button> that was clicked on.

Then you add the new elements into that <div> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM