JavaScript 基础知识-setAttribute & getAttribute

前面讲到了选取元素的方法 .querySelector().querySelectorAll()
选取到了元素,我们就可以对他们设定一些属性,例如设定 id 属性或者 class 属性

以下举个 HTML 结构的例子:

<h1 class="titleClass">    <a href="#">title</a></h1>

如果这时候选取 .titleClass 内的 a 连结的 href 属性,并设置成 https://www.google.com

var el = document.querySelector('.titleClass a');el.setAttribute('href','https://www.google.com');

这时候 a 连结就会连到 google 页面,相反的除了设定属性,我们也可以取得属性:

var get = el.getAttribute('href');console.log(get);

这时候在 console 看,会是 https://www.google.com

setAttribute 方法内欲放的两个参数分别是要设置的属性跟值
.setAttribute('属性','值')

getAttribute 方法欲放的参数,即是要取得的属性
.getAttribute('属性')

大家不妨可以写点 class 或是 id 运用,setAttribute 来套用,看看会有什么效果吧 http://img2.58codes.com/2024/emoticon01.gif


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章