<div id="div1"> <p id="p1"> 我是第一个苹果</p> <p id="p2"> 我是第二个苹果</p> </div> <script> window.onload = function () { var str = document.getElementById("p1").innerHTML;//获取p1标签里的内容,innerHTML内部 alert(str); //弹出 我是第一个苹果 </script> }
<div id="div1"> <p id="p1"> 我是第一个苹果</p> <p id="p2"> 我是第二个苹果</p> <input type="text" value="请输入值" name="userName" /> <input type="button" value="确定" onclick="fun1()"> </div> function fun1() { var username = document.getElementsByName("userName")[0].value; alert(username); //输出userName里输入的值 }
<div id="div1"> <p id="p1"> 我是第一个苹果</p> <p id="p2"> 我是第二个苹果</p> </div> window.onload = function () { var str = document.getElementsByTagName("p")[1].innerHTML; alert(str); //输出 我是第二个p,因为获取的是索引为1的P,索引从0开始 } window.onload = function () { var arr = document.getElementsByTagName("p"); for (var i = 0; i < arr.length; i++) { alert(arr[i].innerHTML); } } window.onload = function () { var node = document.getElementById("div1"); var node1 = document.getElementsByTagName("p")[1]; //从获取到的元素再获取 alert(node1.innerHTML); }
<div id="div1"> <p id="p1" class="class1"> 我是第一个P</p> <p id="p2"> 我是第二个P</p> </div> window.onload = function () { var node = document.getElementsByClassName("class1")[0]; alert(node.innerHTML); }