Heim  >  Artikel  >  Web-Frontend  >  javascript学习笔记(二十) 获得和设置元素的特性(属性)_基础知识

javascript学习笔记(二十) 获得和设置元素的特性(属性)_基础知识

WBOY
WBOYOriginal
2016-05-16 17:52:23935Durchsuche

本节html以下面的为例

复制代码 代码如下:

1.通过HTMLElement类型(对象)的属性获得和设置元素特性
复制代码 代码如下:

var div = document.getElementById("myDiv");
var img = document.getElementById("img1");
var a = document.getElementById("myA");
//取得元素特性
alert(div.id); //"myDiv"
alert(div.className); //"bd",这里不是div.class,是因为class是保留关键字
alert(div.title); //"我是div"
alert(a.href); //http://www.baidu.com
//设置元素特性
div.id = "myDiv2"; //id改为"myDiv2"
div.className = "ft"; //class改为"ft",如果存在名为"ft"的样式,会立刻变为"ft"样式,浏览器会立刻反应出来
div.title = "我是myDiv2"; //title改为"我是myDiv2"
div.align = "center"; //设置居中对齐
img.src ="images/img1.gif"; //设置图片路径
a.innerHTML ="新浪"; //"百度"改为"新浪"
a.href = "http://www.sina.com.cn"; //重新设置超链接

2.通过getAttribute()、setAttribute()和removeAttribute() 方法,获取、设置、移除元素的特性(不推荐使用,前两个方法IE6,7中有异常,第三个方法IE6不支持,设置自定义特性时可以使用)
getAttribute() 方法,用来获取元素特性。接受一个参数,即要获得元素的特性名
setAttribute() 方法,用来设置元素特性。接受两个参数,即要获得元素的特性名和特性值
removeAttribute() 方法,用来移除元素的特性。接受一个参数,即要移除元素的特性名
复制代码 代码如下:

var div = document.getElementById("myDiv");
var img = document.getElementById("img1");
var a = document.getElementById("myA");
//取得元素特性
alert(div.getAttribute("id")); //"myDiv"
alert(div.getAttribute("class")); //"bd",注意这里是class,而不是className,与上面不同
alert(div.getAttribute("title")); //"我是div"
alert(a.getAttribute("href")); //http://www.baidu.com
//设置元素特性
div.setAttribute("id","myDiv2"); //id改为"myDiv2"
div.setAttribute("class","ft"); //class改为"ft",这里同样是class,而不是className
div.setAttribute("title","我是myDiv2"); //title改为"我是myDiv2"
div.setAttribute("align","center"); //设置居中对齐
img.setAttribute("src","images/img1.gif"); //设置图片路径
//移除元素特性
div.removeAttribute("class"); //移除class特性

3.通过attributes属性,获取、设置、移除元素的特性
复制代码 代码如下:

var div = document.getElementById("myDiv");
//取得元素特性
alert(div.attributes["id"].nodeValue); //"myDiv"
//设置元素特性
div.attributes["id"].nodeValue = "myDiv2"; //id改为"myDiv2"
//移除元素特性
div.attributes.removeNamedItem("class"); //移除class特性
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn