1: 获取网页元素的属性值
HTML里面的标签,都有一些属性(attribute),比方:
<img src="http://www.abc.com/logo.png" class='logo' id='logo'>
这里的'href', 'id'和'class'都是这个'<img>'元素的attribute。而在我们的HTMLElement里,定义了与之对应的属性(property),通过引用它们,可以得到这些元素的attribute的价值,例如:
我们可以通过在在我们获取的HTMLElement上用引用这些同名的property,就能获得HTML元素对应的attribute的值。
但是,或许你注意到了,我们使用了'img.className'而不是'img.class'来获取了这个图片元素的class的值。这是因为,从attribute到property,并不是所有的都是同名的,是有一些规则的:
1: HTML的attribute不区分大小写,但是javaScript的property是区分的。所以引用property时,应该用小写。但是对于本身attribute是超过一个单词的,property应该用驼峰,例如:defaultChecked, tabIndex 3: 如果attribute是javaScript的保留字,那对应的property是在attribute前面加'html'。比如'<label for='xxyyzz' id='lableExample'></label>',我们要通过‘htmlFor’来得到‘xxyyzz’. 但是‘class’是一个特殊,它的property是‘className’,而不是‘htmlCss’.
接下来看一个对照表:
2:设置网页元素的属性值
我们通过直接给HTMLElement的property赋值,就可以改变HTML元素的attribute的值。比如我们一开始有一段html:
<img src="http://www.abc.com/logo.png" class='logo' id='logo'>
然后我们通过javaScript来改变它的src:
var img = document.getElementById('logo'); img.src = 'http://www.new.com/logo.png'
这个时候,我们再回去看我们的HTML, img元素的src就已经变了:
3: getAttribute()和setAttribute()
除了上面提到的,可以直接通过property来获取和设置HTML元素的attribute值,javaScript还提供了额外的两个方法:getAttribute()和setAttribute()。还是上面的那个img元素:
<img src="http://www.abc.com/logo.png" class='logo' id='logo'>
1: 使用getAttribute()获取attribute值
var img = document.getElementById('logo'); img.getAttribute('class'); //"logo red"
2: 使用setAttribute()来设置attribute值
var img = document.getElementById('logo'); img.setAttribute('src', 'http://www.new-again.com/logo.png');
咋看好像这两个方法跟上面直接用property是一样的,但是其实它们直接还是有一些差别的:
1: 返回结果类型不一样 1: 通过'element.property'这种方式返回的值的类型,跟attribute值的类型一样。可以是字符串,布尔值得,对象,数字等。 2: 通过'element.getAttribute()'返回的结果都是字符串类型,不管HTML元素的attribute值是什么类型。 2: 对属性名名称的对应规则不一样 1: 通过'element.property'这种方式,property的名字和HTML的attribute不一定一摸一样,有些还要经过转换之类的,比如:class->className, for->htmlFor 2: 通过'element.getAttribute()'呢,参数名字和HTML的attribute名字一模一样,比如:img.getAttribute('class')//参数是‘class’,而不是‘className’ 3: getAttribute()可以获取HTML元素的非标准的attribute值,但是'element.property'却不能。
针对第三点做一个解释,所以的‘非标准attribute’,就是只你自己给HTML元素加的attribute,比如:
<img src="http://www.abc.com/logo.png" class='logo red' id='logo' job='as a logo'>
我们给<img>元素添加了一个‘job’ attribute, 然后尝试用两种不同的方法获取它的值:
var img = document.getElementById('logo'); img.job;//undefined img.getAttribute('job'); //'as a log' img.setAttribute('job', 'hehe');// img元素的job属性的值被改变 img.job = 'ff';//img元素的job的值没有被改变,但是也不会抛错,并且返回'ff' 来源:itnose