JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes

One 获取标签属性

语法:元素 . 属性名

 
    
JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第1张图片
00.png

Two 对合法标签属性操作 →HTML规定的一些标签属性

语法:元素 . 属性名 = ‘xxx’;


    
图一.png

JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第2张图片
图2.png

为什么会报错呢?Cannot set property 'title' of null (不能设置title给空对象)
因为:上面已经修改了id值了 再次通过原来的id值已经获取不到元素了;要用修改后的id值;

利用变量来设置

  var  x = document.getElementById( 'wrap' );
         x.id= 'wrap2';
         x.title = '阿飞';
1.png

为什么可以呢?
因为:x已经在id修改存储了元素了,一直存放在x里面,后面无论对元素修改什么永远也改变不了x里的元素;

特殊 class

我们之前有讲过class是保留词;对class不能直接用class = 直接操作;要通过 className

  x.class = 'box2';修改不了
2.png

通过:

  x.className = 'box2';
JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第3张图片
3.png

修改多个属性值: 属性值与属性值中间用 空格 隔开;

   x.className = 'box2 box3 box4';
JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第4张图片
3.png

Three 不合法标签属性(自定义的标签属性)

 
    
JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第5张图片
4.png

弹出undefined说明没办法获取到→所以针对自定义标签通过 . 操作是无效;

那么用什么呢?
自定义属性三剑客:

  x.getAttribute( ' ' );获取
  x.setAttribute( ' ' );设置
  x.removeAttribute( ' ' );删除



  attributes 查询标签里的属性

getAttribute( ' ' );获取

 
    
JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第6张图片
5.png

x.setAttribute( ' ' );设置

 
    
6.png

也可以进行添加标签属性

 
    
JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第7张图片
7.png

x.removeAttribute( );

 
    
8.png

有人问用

        var x = document.getElementById( 'wrap' );
              x.setAttribute( 'ali' , ' ');
              x.removeAttribute( 'ali'  );
JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第8张图片
9.png

从图片可以看到
x.setAttribute( 'ali' , ' ');只是把属性值变为空、属性名还在;
x.removeAttribute( 'ali' );是把属性名、属性值删掉;

注意:三剑客对合法标签属性也起作用;

attributes 查询标签里的属性

JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第9张图片
图一

图二

JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第10张图片
图三

JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes_第11张图片
图四

你可能感兴趣的:(JaveScript基础4 操作标签属性 getAttribute setAttribute removeAttribute attributes)