Summary of methods for adding elements in JS

Method one creates a node and appends

<body>
    <input type="text" placeholder="请输入信息">
    <button class="one">添加</button>
    <button>删除</button>
    <ul></ul>
</body>
</html>
<script>
    let oBtn = document.querySelectorAll('button')
    let oBinput = document.body.firstElementChild
    let oUl = oBtn[1].nextElementSibling
    oBtn[0].onclick = function () {
        // 给父元素追加li
        if (oBinput.value != '') { //判断文本不为空时追加
            let oLi = document.createElement('li') 
            oLi.innerHTML = oBinput.value
            oUl.appendChild(oLi)
            oBinput.value = ''
        }
    }
    </script>

insert image description here

Method 2 concatenating strings

<script>
    let oBtn = document.querySelectorAll('button')
    let oBinput = document.body.firstElementChild
    let oUl = oBtn[1].nextElementSibling
    let str = ''
    oBtn[0].onclick = function () {
        str += `    <li>${oBinput.value}</li>
  `
        oBinput.value = ''
        oUl.innerHTML = str
             }
    </script>

Method 3 uses insertBefore

Function : Add child elements according to the specified position, before adding the target element to the reference element
Usage : parent element.insertBefore(target element, reference element)

//body内容同上
<script>
    let oBtn = document.querySelectorAll('button')
    let oBinput = document.body.firstElementChild
    let oUl = oBtn[1].nextElementSibling
    oBtn[0].onclick = function () {
          if (oBinput.value != '') {
            let oLi = document.createElement('li')
            oLi.innerHTML = oBinput.value //赋值
            oUl.insertBefore(oLi, oUl.lastElementChild)
            oBinput.value = ''

        } 
        }
    </script>

insert image description here

Guess you like

Origin blog.csdn.net/m0_67859656/article/details/127993444