前端技术-操作DOM元素

  1. HTML属性和DOM属性的对应关系
    每个HTML元素的属性都有对应的DOM对象属性

     <div>
       <label for="userName">用户名:</label>
       <input id="userName" type="text" class="u-txt"/>
     </div>
    
     input.id; //"userName"
     input.type; //"text"
     input.className; //"u-txt"
     label.htmlFor; //"userName"

2.属性操作的方式

  • property accessor(属性访问器)

    • 读取元素属性
        input.className; //"u-txt"
        input["id"]; //等价于input.id,"userName"
    • 写入元素属性
        input.value = "www.baidu.com"; //在input元素节点增加value属性,设置它的值为"www.baidu.com"
    • 获取元素的类型,转换过的实用对象

        <input class="u-txt" maxlength="10" disabled onclick="showSuggest();" />
      
        input.className; //"u-txt", String
        input.maxlength; //10, Number
        input.disabled; //true, Boolean
        input.onclick; //Function
    • 特点
      通用性差,名字异常;扩展性差;优势是获取的元素类型为实用对象
  • getAttribute/setAttribute

    • 读取属性,var attr = element.getAttrubute(attrubuteName);

        <div>
          <label for="userName">用户名:</label>
          <input id="userName" type="text" class="u-txt"/>
        </div>
      
        input.getAttribute("class"); //u-txt
    • 写入属性,element.setAttribute(name, value);

        <div>
          <label for="userName">用户名:</label>
          <input id="userName" type="text" class="u-txt"/>
        </div>
      
        input.setAttribute("value", "www.baidu.com"); 
        input.setAttribute("disabled", "");
    • 获取元素的类型,属性字符串

        <input class="u-txt" maxlength="10" disabled onclick="showSuggest();" />
      
        input.getAttribute("class"); //"u-txt", String
        input.getAttribute("maxlength"); //"10", String
        input.getAttribute("disabled"); //"", String
        input.getAttribute("onclick"); //"showSuggest()", String
    • 特点
      获取属性值为字符串,通用性强
  • dataset(自定义属性)

    • 定义
      • 形式为HTMLElement.dataset,即HTMLElement元素自定义的属性
      • 名称为data-*,即data-开头加名称
      • 用于元素上用户自定义的数据保存
      • 数据通常使用 AJAX 获取并存储在节点之上
    • 示例

      <div id='user' data-id='123456' data-accountName='nc' data-email='mail@gmail.com'></div>
      
      div.dataset.id; //'123456'
      div.accountName; //'nc'
      div.dataset.email; //'mail@gmail.com'

转载于:https://www.cnblogs.com/yileye/articles/7691883.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值