元素的属性及样式设置

元素的属性

元素就是标签

  1. 获取元素
  2. 设置元素属性
  3. 删除元素属性

<body>
    <header id="head" class="head1" name="head2" name1="head3" style="height: 100px;">这里是头部标签</header>
    <button id="set">设置</button>
    <button onclick="fn1()">删除</button>
</body>

获取元素属性的方法getAttribute(‘属性名’)

// 获取元素属性的方法 getAttribute('属性名')
    console.log(head.getAttribute('id'));
    console.log(head.getAttribute('class'));
    console.log(head.getAttribute('name'));
    console.log(head.getAttribute('name1'));
    console.log(head.getAttribute('style'));

设置元素属性:setAttribute(‘属性名’,‘属性值’)

 // 设置元素的属性  setAttribute('属性名','属性值')
    document.getElementById('set').onclick = function () {
        head.setAttribute('id', 'he1')
        head.setAttribute('class', 'he2')
        head.setAttribute('name2', 'he3')
    }

删除元素属性  removeAttribute(‘属性名’)

// 删除元素的属性  removeAttribute('属性名')
    function fn1() {
        // console.log('测试');
        head.removeAttribute('id')
        head.removeAttribute('class')
        head.removeAttribute('name')
        head.removeAttribute('style')
    }

元素的样式设置

样式的设置方式:

  1. 对象.style
  2. 对象.className
  3. 对象.setAttribute(‘style’)
  4. 对象.setAttribute(‘class’)
  5. 对象.style.setProperty(‘css属性名’,’css属性值’)
  6. 对象.style.cssText
    <script>
        /*   
        1、对象.style
        2、对象.className
        3、对象.setAttribute('style')
        4、对象.setAttribute('class')
        5、对象.style.setProperty('css的属性名','css属性值')
        6、对象.style.cssText
        */
    
        document.getElementsByClassName('btn')[0].onclick = function () {
            // console.log('测试');
            // 1、
            // document.getElementById('head').style.backgroundColor = 'red'
            // 2、
            // document.getElementById('head').className = 'head'
            // 3、
            // document.getElementById('head').setAttribute('style', 'background-color:red')
            // 4、
            // document.getElementById('head').setAttribute('class', 'head')
            // 5、
            // document.getElementById('head').style.setProperty('background-color', 'red')
            // 6、
            document.getElementById('head').style.cssText = 'background-color: red;height:200px;'
    
        }
    
    </script>
       

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值