问答详情
源自:9-9 访问子节点的第一和最后项

刚写完分享下答案

<!DOCTYPE HTML>

<html>

<head>

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

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

</head>

<body>

<!--<div id="con">-->

<!--  <p>javascript</p>-->

<!--  <div>jQuery</div>-->

<!--  <h5>PHP</h5>-->

<!--</div>-->

<div id="con"><p>javascript</p><div>jQuery</div><h5>PHP</h5></div>

<script type="text/javascript">

  var x=document.getElementById("con");

  function write(a){

        document.write("节点的名称:"+a.nodeName+"<br/>");

        document.write("节点的值:"+a.nodeValue+"<br/>");

        document.write("节点的类型:"+a.nodeType+"<br/>");

        document.write("-----------------------"+"<br/>");

  } 

  write(x.firstChild);

  write(x.lastChild);

</script>

</body>

</html>


提问者:逃离外包 2019-01-29 10:07

个回答

  • jalone
    2019-05-24 16:18:13

    document.write(document.getElementById("con").firstChild.nodeType+"<br />"+document.getElementById("con").firstChild.nodeName)

  • bao_
    2019-04-20 09:32:04

    非常棒!

  • 慕容6478286
    2019-03-30 11:56:24

    <!DOCTYPE HTML>

    <html>

    <head>

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

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

    </head>

    <body>


    <div id="con">

      <p>javascript</p>

      <div>jQuery</div>

      <h5>PHP</h5>

      </div>


    <div id="con"><p>javascript</p><div>jQuery</div><h5>PHP</h5></div> 

    <script type="text/javascript">

      var x=document.getElementById("con");

     document.write("指定元素的第一个子节点"+x.firstChild.nodeName+" "+x.firstChild.nodeValue+" "+x.firstChild.nodeType+"<br/>");

     document.write("指定元素的最后一个子节点"+x.lastChild.nodeName+" "+x.firstChild.nodeValue+" "+x.firstChild.nodeType);

    </script>

    </body>

    </html>