DOM简介:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dom简介</title>
</head>
<body>
<div id="intro">hello world</div>
<div id="main">
<p>The DOM is very useful.</p>
</div>
<div class="content">1</div>
<div class="content">2</div>
<div class="content">3</div>
<div class="content">4</div>
<script type="text/javascript">
// 通过js获取html标签
var intro = document.getElementById("intro"); //通过id找html,唯一的
var main = document.getElementById("main");
// main.getElementsByTagName("p"); //会找到所有的p, 返回一个数组
var p = main.getElementsByTagName("p")[0];
var content1 = document.getElementsByClassName("content")[0];
</script>
</body>
</html>
DOM-HTML:
将div内的123修改为helloworld:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM-HTML</title>
</head>
<body>
<div id="main" data="1">123</div>
<script>
var main = document.getElementById("main");
main.innerHTML = "helloworld";
</script>
</body>
</html>
alert(main.getAttribute("data")); //出现弹框显示属性值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM-HTML</title>
</head>
<body>
<div id="main" data="1">123</div>
<img src="1.jpg" id="image">
<a id="goUrl" href="">跳转到百度</a>
<script>
var main = document.getElementById("main");
main.innerHTML = "helloworld";
// alert(main.getAttribute("data")); //出现弹框显示属性值
main.setAttribute("data", "2"); //修改
main.setAttribute("data1", "22"); //添加
var image = document.getElementById("image");
image.src = "2.jpg"; //直接修改图片的属性
var goUrl = document.getElementById("goUrl");
goUrl.href = "http://www.baidu.com"; //赋值或直接修改
</script>
</body>
</html>