您的位置:首页 > Web前端 > JavaScript

javascript 获取和设置属性getAttribute setAttribute

2016-12-25 15:18 399 查看
getAttribute只有一个参数,所查询属性的名字

使用方法:object.getAttribute(attribute);

var pas=document.getElementsByTagName("p");

for(var i=0;i<pas.length;i++){
var titleText=pas[i].getAttribute("title");
if(titleText != null)
{
alert(titleText);}}

//测试结果为:

setAttibute 用法

<script type="text/javascript">

var pas=document.getElementsByTagName("p");

for(var i=0;i<pas.length;i++){
var titleText=pas[i].getAttribute("title");
if(titleText != null)
{
pas[i].setAttribute("title","a new title");
alert(pas[i].getAttribute("title"));
}

}

源代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>无标题文档</title>

</head>

<body>

<p title="this is a story">  依兰爱情故事</p>

<p > this is only a story</p>

<ol id="feel"></ol>

<li>感人</li>

<li>内涵</li>

<script type="text/javascript">

var pas=document.getElementsByTagName("p");

for(var i=0;i<pas.length;i++){
var titleText=pas[i].getAttribute("title");
if(titleText != null)
{
alert(titleText);
pas[i].setAttribute("title","a new title");
alert(pas[i].getAttribute("title"));
}

}

</script> 

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐