1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > JS setAttribute()方法:设置元素的属性值

JS setAttribute()方法:设置元素的属性值

时间:2022-02-23 21:11:15

相关推荐

JS setAttribute()方法:设置元素的属性值

在JavaScript中,使用元素的 setAttribute() 方法可以设置元素的属性值。用法如下:

setAttribute(name, value)

参数 name 和 value 分别表示属性名称和属性值。属性名和属性值必须以字符串的形式进行传递。如果元素中存在指定的属性,它的值将被刷新;如果不存在,则setAttribute() 方法将为元素创建该属性并赋值。

示例1

下面示例分别为页面中 div 元素设置 title 属性。

<div id="red">红盒子</div><div id="blue">蓝盒子</div><script>var red = document.getElementById("red"); //获取红盒子的引用var blue= document.getElementById("blue"); //获取蓝盒子的引用red.setAttribute("title", "这是红盒子"); //为红盒子对象设置title属性和值blue.setAttribute("title", "这是蓝盒子"); //为蓝盒子对象设置title属性和值</script>

示例2

下面示例定义了一个文本节点和元素节点,并为一级标题元素设置 title 属性,最后把它们添加到文档结构中。

var hello = document.createTextNode("Hello World!"); //创建一个文本节点var h1 = document.createElement("h1"); //创建一个一级标题h1.setAttribute("title", "你好,欢迎光临!"); //为以及标题定义title 属性h1.appendChild(hello); //把文本节点增加到一级标题中document.body.appendChild(h1); //把一级标题增加到文档

m.setAttribute("style", "background-color: #ccc;");

div.innerHTML = 'new value';

示例3

也可以使用快捷方法设置 HTML DOM 文档中元素的属性值。

<label id="label1">文本框:<input type="text" name="textfield" id="textfield" /></label><script>var label1 = document.getElementById("label1");label.className = "class1";label.htmlFor = "textfield";</script>

DOM 支持使用 getAttribute() 和 setAttribute() 方法读写自定义属性,不过 IE 6.0 及其以下版本浏览器对其的支持不是很完善。

示例4

直接使用 className 添加类样式,会覆盖掉元素原来的类样式。这时可以采用叠加的方式添加类。

<div id="red">红盒子</div><script>var red = document.getElementById("red");red.className = "red";red.className += "blue";</script>

示例5

使用叠加的方式添加类也存在问题,这样容易添加大量重复的类。为此,定义一个检测函数,判断元素是否包含指定的类,然后再决定是否添加类。

纯文本复制

<script>function hasClass (element, className) { //检测类名函数var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');return reg.test(element.className); //使用正则检测是否有相同的样式}function addClass (element, className) { //添加类名函数if (! hasClass (element, className))element.className += ' ' + className;}</script><div id="red">红盒子</div><script>var red = document.getElementById("red");addClass(red, 'red');addClass(red, 'blue');</script>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。