自定义元素节点/属性

顾名思义,自定义也就是自己创建一个,通过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框在指定的盒子里

创建一个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只是为了让看得更清楚才让它挤下来超出父级盒子,平时布局最好不要这么写哦!!

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐