Menu

7/26/20

DOM HTML
























DOM (document object model) dùng để truy xuất các đối tượng (elements) trong tài liệu HTML và XML, có dạng cấu trúc cây dữ liệu.

Các phương thức truy xuất trong DOM

-document.getElementByID ('id_cần_tìm')
-document.getElementBytagName('body')
-document.getElementByName ('abc')

Ta có thể truy xuất nội dung các elements trong DOM bằng thuộc tính (attribute): InnerHTML

Sử dụng phương thức bytagName:

    <script>
        function F()
        {
            var v1 = document.frm1.n.value;
            document.getElementsByTagName('body')[0].bgColor=v1;

        }
    </script>
   
    <form action="" name="frm1">
        color<input type="color" name="n" id='id1'>
        <input type="button" onClick="F()" value="Chay F">
       
    </form>

- Sử dụng phương thức byid hiện/ẩn image trong thẻ div

 <script>
       function hien(){
            var dir=document.fm1.x.value;
            var insert="<img src=" '+dir+' ">";
            document.getElementById('div1').innerHTML+=insert;
        }
        function xoa(){
            document.getElementById('div1').innerHTML="";
        }
       
    </script>
</head>
<body>
    <form action="" name="fm1">
        <input type="text" id="x"><br>
        <input type="button" onclick="hien()" value="hien" ><br>
        <input type="button" onclick="xoa()" value="xoa"><br>
    </form>

 
 -  Attribute (thuộc tính) trong DOM


 <p id="myid" onclick="F1()">this is a text</p>
    <script>
            var x1 = document.getElementById("myid").attributes[0].name;
            var x2 = document.getElementById("myid").attributes[1].name;
            var x3 = document.getElementById("myid").attributes[0].value;
            var x4 = document.getElementById("myid").attributes[1].value;
            var x=[x1,x2,x3,x4];
            console.log(x);

    </script>

----------Kết quả:

  1. (4) ["id", "onclick", "myid", "F1()"]
    1. 0"id"
    2. 1"onclick"
    3. 2"myid"
    4. 3"F1()"
    5. length4
--In ra các childnode:

html>
  <head>
    <title>HTML DOM Demonstration</title>
  </head>

  <body>
    <h1>Headings</h1>
    <p>Hello world!</p>
    <script>

        var x= document.body.childNodes;
        console.log(x);    //;
    </script>
  </body>
</html>

-------kết quả:

NodeList(6) [text, h1, text, p, text, script]
0: text
1: h1
2: text
3: p
4: text
5: script
6: text
length: 7
      

No comments:

Post a Comment