1.操作标签属性:
形式:
对象.属性名=“属性值”:
源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>标签的属性</title>
</head>
<body>
<img src="images/1.jpg" alt="我是alt222" title="我是title" nj="666">
<script type="text/javascript">
//获取
let oImg=document.querySelector("img");
console.log(oImg.alt);
console.log(oImg.getAttribute("nj"));
// 2.修改
/*let oImg1=document.querySelector("img");
oImg1.title="新的title";
oImg1.setAttribute("nj","123"); */
// 3.增加
/*let oImg2=document.querySelector("img");
oImg2.setAttribute("it666","itzb");*/
// 4.删除
/*let oImg3=document.querySelector("img");
oImg3.alt="";
oImg3.removeAttribute("nj");*/
</script>
</body>
</html>
最后总结:
对象.属性是对系统自带的属性进行操作.
Attribute是对自己写的属性进行操作。(自定义)
效果图;
获取:
修改:
增加
删除
2.操作标签内容
形式;
对象.属性名=“属性值”;
源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
我是div
<h1>我是标题</h1>
<p>我是段落</p>
</div>
<script type="text/javascript">
//获取标签的容.
let oDiv=document.querySelector("div");
console.log(oDiv.innerHTML);
console.log(oDiv.innerText);
console.log(oDiv.textContent);
//修改标签内容
let oDiv1=document.querySelector("div");
oDiv1.innerHTML = "<span>我是span</span>";
oDiv1.innerText = "<span>我是span1</span>";
oDiv1.textContent = "<span>我是span2</span>";
</script>
</body>
</html>
1.1获取.
let oDiv=document.querySelector("div");
console.log(oDiv.innerHTML);
console.log(oDiv.innerText);
console.log(oDiv.textContent);
效果:
1.2设置
let oDiv1=document.querySelector("div");
oDiv1.innerHTML = "<span>我是span</span>";
oDiv1.innerText = "<span>我是span1</span>";
oDiv1.textContent = "<span>我是span2</span>";
效果:
总结:
1:innerHTML/innerText/textContent都是设置给HTML标签上的.
2:因为这三个都是作用在HTML标签上的,所以会产生后面的会覆盖掉前面的.
3:操作元素样式
形式;
对象.style.属性名=“属性值”:
源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div></div>
<script type="text/javascript">
//设置
let oDiv = document.querySelector("div");
oDiv.style.width="300px";
oDiv.style.height="300px";
oDiv.style.backgroundColor="blue";
//获取
let oDiv1 = document.querySelector("div");
oDiv.style.width = "300px";
console.log(oDiv.style.width);
</script>
</body>
</html>
//设置:
let oDiv = document.querySelector("div");
oDiv.style.width="300px";
oDiv.style.height="300px";
oDiv.style.backgroundColor="blue";
效果:
获取
let oDiv1 = document.querySelector("div");
oDiv.style.width = "300px";
console.log(oDiv.style.width);
效果:
总结;
1;js中操作css只能通过行内来做.