javascript学习笔记(二十) 获得和设置元素的特性(属性)
本节html以下面的为例
1.通过HTMLElement类型(对象)的属性获得和设置元素特性
2.通过getAttribute()、setAttribute()和removeAttribute() 方法,获取、设置、移除元素的特性(不推荐使用,前两个方法IE6,7中有异常,第三个方法IE6不支持,设置自定义特性时可以使用)
getAttribute() 方法,用来获取元素特性。接受一个参数,即要获得元素的特性名
setAttribute() 方法,用来设置元素特性。接受两个参数,即要获得元素的特性名和特性值
removeAttribute() 方法,用来移除元素的特性。接受一个参数,即要移除元素的特性名
3.通过attributes属性,获取、设置、移除元素的特性
<div id="myDiv" class="bd" title="我是div">
<img id="img1" />
<a id="myA" href = "http://www.baidu.com">百度</a>
</div>
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特性
JavaScript基础知识之数据类型
数据类型JavaScript中有5种简单数据类型(也称为基本数据类型):Undefined、Null、Boolean、Number和String。还有1种复杂数据类型——Object,Object本质上是由一
JS数学函数Exp使用说明
计算ex摘要Math.exp(x)参考x数值或表达式,被用作指数。返回值ex,即e的x次幂。这里e代表自然对数的底数,其近似为2.71828。exp()语法如下:Math.exp(x);Math.ex
JavaScript之引用类型介绍
Object类型Object类型是JavaScript中使用最多的一种类型。虽然Object的实例不具备多少功能,但对于在应用程序中存储和传输数据而言,它确实是非常理想的
想了解相关产品?
扫码添加企业微信,预约演示。
