2025年4月25日 星期五 乙巳(蛇)年 正月廿六 夜 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Html+Div+Css(前端)

js属性节点获取和移除

时间:07-16来源:作者:点击数:37

关于节点类型不再重复解释,不懂可以看《js节点都有哪些类型?怎么判断是哪种节点类型?

公共html代码:

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <meta charset="UTF-8">
  • <title></title>
  • </head>
  • <body>
  • <div id="bb">
  • <div class="box1"></div>
  • <div class="box">
  • <p title="hhhh">第1</p>
  • <p dataId="2">第2</p>
  • <p>第3</p>
  • <p>第4</p>
  • </div>
  • <div class="box2"></div>
  • </div>
  • </body>
  • </html>

1.属性节点获取

第一种方法就是直接获取html自带的属性例如:alt,title,href,placeholder... 注意:不用用来获取自定义属性

  • console.log(pp.children[0].title); //hhhh
  • console.log(pp.children[1].dataId); //undefined

第二种方法 getAttribute()获取

  • console.log(pp.children[0].getAttribute('title')); //hhhh
  • console.log(pp.children[1].getAttribute('dataId')); //2

属性节点删除:removeAttribute()

  • pp.children[1].removeAttribute('dataId'); //删除节点属性
  • console.log(pp.children[1].getAttribute('dataId')); //null
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门