• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

JS自定义元素节点/属性的使用 createElement、setAttribute、getAttribute、appendChild

武飞扬头像
荧惑
帮助9

自定义元素节点/属性

顾名思义,自定义也就是自己创建一个,通过JS生成节点或者属性,而不是在html里写的。

如何创建

创建元素节点

createElement:创建一个元素节点,但里面是空的,
一般使用都是document.createElement,在文档中创建,这样可以将创建的加到任意想要的位置;
appendChild(a):将创建出来的节点a追加到指定元素里的最后面,和insertBefore相反;
document.body.insertBefore(a, b):在body里面的b之前添加a,()里的参数必须为两个;

被加的都最好是命名(var)一个id变成节点 不能直接填写例如 div span p 这样的(非节点)关键字

自定义元素属性

setAttribute(name, value):设置/添加元素节点的属性,有则设置,无则添加;
getAttribute;获取元素节点的属性;
removeAttribute:清除属性;

实列:创建一个input框在指定的盒子里

学新通

学新通

  • 添加的属性必须用引号引起来,要不然会被当做成一个变量,就会报错。

学新通
学新通

通过getAttribute获取需要的属性值
JS:

<script>
    var a = ipt.getAttribute('disabled')
    console.log(a);
</script>

如果想要添加到指定的盒子之后可以使用转到父节点追加

学新通
总代码:
html:

<body>
    <div class="box"></div>
</body>

css:

<style>
        .box {
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        
        input {
            margin-top: 100px;
        }
</style>

js:

<script>
        window.onload = function() {
            var box = document.querySelector('.box')
            var ipt = document.createElement('input')
            ipt.setAttribute('type', 'button')
            ipt.setAttribute('value', '按钮')
            ipt.setAttribute('disabled', 'disabled')
            ipt.setAttribute('name', 'value')
            var a = ipt.getAttribute('disabled')
            console.log(a);
            box.appendChild(ipt)
                // box.parentElement.appendChild(ipt)
        }
</script>

注意:这里的margin只是为了让看得更清楚才让它挤下来超出父级盒子,平时布局最好不要这么写哦!!

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhfhibc
系列文章
更多 icon
同类精品
更多 icon
继续加载