DOM操作

作者: jiangzj | 来源:发表于2019-03-05 13:08 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <!--
        1.整个文档是一个文档节点
        2.每个 HTML 元素是元素节点
        3.HTML 元素内的文本是文本节点
        4.每个 HTML 属性是属性节点
        5.注释是注释节点
    -->
    <div class="wrap">
        <input type="checkbox">
        <input type="checkbox">
        <input type="text">
    </div>

    <script>
        const log = console.log.bind(console)

        const findElement = (sel) => {
          const ele = document.querySelector(sel)
          return ele
        }

        const findElements = (sel) => {
          const ele = document.querySelectorAll(sel)
          return ele
        }

        const findElementByAttr = (sel, attr, val) => {
          const es = findElements(sel)
          const result = []
          // NodeList 并不是 Array
          es.forEach(e => {
            if (e.getAttribute(attr) === val) {
              result.push(e)
            }
          })
          return result
        }

        const createElement = (tag) => {
          const ele = document.createElement(tag)
          return ele
        }

        const createTextNode = (str) => {
          const node = document.createTextNode(str)
          return node
        }


        const main = () => {
          let parent = findElement('.wrap')
          let child = createElement('p')
          let text = createTextNode('haha')
          let text1 = createTextNode('heihei')

          child.appendChild(text)
          parent.appendChild(child)
          child.replaceChild(text1, text)
          parent.removeChild(child)

          let textInput = findElementByAttr('input', 'type', 'text')
          parent.insertBefore(child, textInput[0])


          let checkbox = findElementByAttr('input', 'type', 'checkbox')
          log('checkbox', checkbox)
        }
        main()


    </script>
</body>
</html>

相关文章

网友评论

      本文标题:DOM操作

      本文链接:https://www.haomeiwen.com/subject/xwvnuqtx.html