className与get / setAttribute方法 [英] className vs. get/setAttribute method

查看:154
本文介绍了className与get / setAttribute方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了两种获取属性值的方法:
首先是:

  document.getElementById ( ID)的getAttribute( 类); 
document.getElementById(id)。setAttribute(class,newClass);

其他:

 的document.getElementById( ID)的className。 

两者都可用于设置和获取类值或任何其他值。是否有特定的情况,哪一个更可取?一个比另一个快吗?他们有什么不同?为什么有两种方法呢?

解决方案

他们做了不同的事情。 .getAttribute('name')获取属性,而 .name 获取属性。



该属性是元素创建时由HTML代码中的属性设置的初始值。该属性是当前值,自创建该元素后可能会发生更改。



对于某些属性,属性随属性一起更改,但对于某些属性和属性是分开的值:

window.onload = function(){var el = document.getElementById(id); console.log(Attribute:+ el.getAttribute(value)); console.log(Property:+ el.value); console.log('更改属性'); el.value ='b'; console.log(Attribute:+ el.getAttribute(value)); console.log(Property:+ el.value); };

< input type =textid = idvalue =a>< / div>

I have come across 2 ways of getting a value of attribute: first is:

document.getElementById("id").getAttribute("class");
document.getElementById("id").setAttribute("class", "newClass");

the other:

document.getElementById("id").className;

Both can be used to set and get class value or any other value. Are there specific situations where one is preferable? Is one faster than the other? How do they differ? Why even have 2 ways of doing it?

解决方案

They do different things. The .getAttribute('name') gets the attribute, while .name get the property.

The attribute is the initial value set by the attribute in the HTML code when the element is created. The property is the current value, which may have changed since the element was created.

For some properties the attribute change along with the property, but for some the property and attribute are separate values:

window.onload = function(){
  
  var el = document.getElementById("id");

  console.log("Attribute: " + el.getAttribute("value"));
  console.log("Property: " + el.value);

  console.log('Changing property');
  el.value = 'b';

  console.log("Attribute: " + el.getAttribute("value"));
  console.log("Property: " + el.value);
  
};

<input type="text" id="id" value="a"></div>

这篇关于className与get / setAttribute方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆