본문 바로가기

22년 2학기 학교공부

JS HTML DOM

목차

    728x90
    반응형
    SMALL

    JavaScript HTML DOM(Document Object Model)

    - When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects

    <html>
     <head> 
      <title> My title</title>
     </head>
     <body>
      <a href=“” > My Link</a>
      <h1> My header</h1>
     </body>
    </html>

     

    With the object model, JavaScript gets all the power it needs to create dynamic HTML:

    JavaScript can change all the HTML elements in the page. JavaScript can change all the HTML attributes in the page. JavaScript can change all the CSS styles in the page. JavaScript can remove existing HTML elements and attributes. JavaScript can add new HTML elements and attributes JavaScript can react to all existing HTML events in the page. JavaScript can create new HTML events in the page.

     

    What is the DOM?

    A W3C (World Wide Web Consortium) standard Defines a standard for accessing documents ◼ “The W3C Document Object Model(DOM) is platform and languageneutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.” Separated into 3 different parts ◼ Core DOM – standard model for all document types ◼ XML DOM – standard model for XML documents ◼ HTML DOM – standard model for HTML documents

     

    What is the HTML DOM?

    A standard object model and programming interface for HTML. It defines: ◼ The HTML elements as objects ◼ The properties of all HTML elements ◼ The methods to access all HTML elements ◼ The events for all HTML elements In other words : The HTML DOM is a standard for how to get, change, add, or delete HTML elements

     

     

    JavaScript - HTML DOM Methods

    The DOM Programming Interface

    The HTML DOM can be accessed with JavaScript (and with other programming languages).

    In the DOM, all HTML elements are defined as objects.

    The programming interface is the properties and methods of each object.

      - A property is a value that you can get or set (like changing the content of an HTML element).

      - A method is an action you can do (like add or deleting an HTML element).

     

     

    JavaScript HTML DOM Document

    The HTML DOM Document Object

    The document object represents your web page.

    If you want to access any element in an HTML page, you always start with accessing the document object.

     

    Finding HTML Objects

    Finding HTML Elements

    The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5. Later, in HTML DOM Level 3, more objects, collections, and properties were added.

     

    There are several ways to do this

    - Finding HTML elements by id

    - Finding HTML elements by tag name

    - Finding HTML elements by class name

    - Finding HTML elements by CSS selectors

    - Finding HTML elements by HTML object collections

     

    Finding HTML Element by Id

    The easiest way to find an HTML element in the DOM, is by using the element id

    If the element is found, the method will return the element as an object (in element)

    If the element is not found, element will contain null

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML DOM</h2>
    
    <p id="intro">Finding HTML Elements by Id</p>
    <p>This example demonstrates the <b>getElementsById</b> method.</p>
    
    <p id="demo"></p>
    
    <script>
    const element = document.getElementById("intro");
    
    document.getElementById("demo").innerHTML = 
    "The text from the intro paragraph is: " + element.innerHTML;
    
    </script>
    
    </body>
    </html>

     

    Finding HTML Elements by Tag Name

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML DOM</h2>
    
    <p>Finding HTML Elements by Tag Name.</p>
    <p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
    
    <p id="demo"></p>
    
    <script>
    const element = document.getElementsByTagName("p");
    
    document.getElementById("demo").innerHTML =
    'The text in first paragraph (index 0) is: ' + element[0].innerHTML;
    
    </script>
    
    </body>
    </html>

     

    Finding HTML Elements by Class Name

    If you want to find all HTML elements with the same class name, use getElementsByClassName( )

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML DOM</h2>
    
    <p>Finding HTML Elements by Class Name.</p>
    <p class="intro">Hello World!</p>
    <p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>
    
    <p id="demo"></p>
    
    <script>
    const x = document.getElementsByClassName("intro");
    document.getElementById("demo").innerHTML = 
    'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
    </script>
    
    </body>
    </html>

     

    Finding HTML Elements by CSS Selectors

    If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll( ) method

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML DOM</h2>
    
    <p>Finding HTML Elements by Query Selector</p>
    <p class="intro">Hello World!.</p>
    <p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p>
    
    <p id="demo"></p>
    
    <script>
    const x = document.querySelectorAll("p.intro");
    document.getElementById("demo").innerHTML = 
    'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
    </script>
    
    </body>
    </html>

     

    Finding HTML Elements by HTML Object Collections

    The following HTML object (and object collections) are also accessible

    - document.anchors

    - document.body

    - document.documentElement

    - document.embeds

    - document.forms

    - document.head

    - document.images

    - document.links

    - document.scripts

    - document.title

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML DOM</h2>
    <p>Finding HTML Elements Using <b>document.forms</b>.</p>
    
    <form id="frm1" action="/action_page.php">
      First name: <input type="text" name="fname" value="Donald"><br>
      Last name: <input type="text" name="lname" value="Duck"><br><br>
      <input type="submit" value="Submit">
    </form> 
    
    <p>These are the values of each element in the form:</p>
    
    <p id="demo"></p>
    
    <script>
    const x = document.forms["frm1"];
    let text = "";
    for (let i = 0; i < x.length ;i++) {
      text += x.elements[i].value + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
    </script>
    
    </body>
    </html>

     

    Changing HTML Elements

    Changing HTML Elements

    Changing HTML Content

    The easiest way to modify the content of an HTML element is by using the innerHTML property

    document.getElementById(id).innerHTML = new HTML

     

    Changing the Value of an Attribute

    document.getElementById(id).attribute = new value
    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML DOM</h2>
    <img id="image" src="smiley.gif" width="160" height="120">
    
    <script>
    document.getElementById("image").src = "landscape.jpg";
    </script>
    
    <p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
    
    </body>
    </html>

     

    Dynamic HTML content

    <!DOCTYPE html>
    <html>
    <body>
    
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = "Date : " + Date();
    </script>
    
    </body>
    </html>

     

    Document.write()

    Can be used to write directly to the HTML output stream

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Bla, bla, bla</p>
    
    <script>
    document.write(Date());
    </script>
    
    <p>Bla, bla, bla</p>
    
    </body>
    </html>

     

    Changing HTML Style

    document.getElementById(id).style.property = new style
    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML DOM</h2>
    <p>Changing the HTML style:</p>
    
    
    <p id="p1">Hello World!</p>
    <p id="p2">Hello World!</p>
    
    <script>
    document.getElementById("p2").style.color = "blue";
    document.getElementById("p2").style.fontFamily = "Arial";
    document.getElementById("p2").style.fontSize = "larger";
    </script>
    
    
    </body>
    </html>

     

    Using Events

    The HTML DOM allows you to execute code when an event occurs

    Events are generated by the browser when “things happen” to HTML elements

      - An element is clicked on

      - The page has loaded

      - Input fields are changed

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1 id="id1">My Heading 1</h1>
    
    <button type="button" 
    onclick="document.getElementById('id1').style.color = 'red'">
    Click Me!</button>
    
    </body>
    </html>

     

    Adding and Deleting Elements

    Adding and Deleting Elements

     

    Adding Events Handlers

    Adding Events Handlers

    Reacting to Events

    To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute.

     

    Examples of HTML events

    - When a user clicks the mouse

    - When a web page has loaded

    - When an image has been loaded

    - When the mouse moves over an element

    - When an input field is changed

    - When an HTML form is submitted

    - When a user strokes a key

     

    HTML Event Attributes

    To assign events to HTML elements you can use event attributes

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML Events</h2>
    <p>Click the button to display the date.</p>
    
    <button onclick="displayDate()">The time is?</button>
    
    <script>
    function displayDate() {
      document.getElementById("demo").innerHTML = Date();
    }
    </script>
    
    <p id="demo"></p>
    
    </body>
    </html>

     

    Assign Events Using the HTML DOM

    The HTML DOM allows you to assign events to HTML elements using JavaScript

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML Events</h2>
    <p>Click "Try it" to execute the displayDate() function.</p>
    
    <button id="myBtn">Try it</button>
    
    <p id="demo"></p>
    
    <script>
    document.getElementById("myBtn").onclick = displayDate;
    
    function displayDate() {
      document.getElementById("demo").innerHTML = Date();
    }
    </script>
    
    </body>
    </html>

     

    The onload and onunload Events

    The onload and onunload events are triggered when the user enters or leaves the page

    The onload event can be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information

    The onload and onunload events can be used to deal with cookies

    <!DOCTYPE html>
    <html>
    <body onload="checkCookies()">
    
    <h2>JavaScript HTML Events</h2>
    
    <p id="demo"></p>
    
    <script>
    function checkCookies() {
      var text = "";
      if (navigator.cookieEnabled == true) {
        text = "Cookies are enabled.";
      } else {
        text = "Cookies are not enabled.";
      }
      document.getElementById("demo").innerHTML = text;
    }
    </script>
    
    </body>
    </html>

     

    The onchange Event

    The onchange event is often used in combination with validation of input fields

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript HTML Events</h2>
    Enter your name: <input type="text" id="fname" onchange="upperCase()">
    <p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
    
    <script>
    function upperCase() {
      const x = document.getElementById("fname");
      x.value = x.value.toUpperCase();
    }
    </script>
    
    </body>
    </html>

     

    The onmouseover and onmouseout Events

    The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element

    <!DOCTYPE html>
    <html>
    <body>
    
    <div onmouseover="mOver(this)" onmouseout="mOut(this)" 
    style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
    Mouse Over Me</div>
    
    <script>
    function mOver(obj) {
      obj.innerHTML = "Thank You"
    }
    
    function mOut(obj) {
      obj.innerHTML = "Mouse Over Me"
    }
    </script>
    
    </body>
    </html>

     

    The onmousedown, onmouseup and onclick Events

    The onmousedown, onmouseup, and onclick events are all parts of mouse-click.

    First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.

    <!DOCTYPE html>
    <html>
    <body>
    
    <div onmousedown="mDown(this)" onmouseup="mUp(this)"
    style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
    Click Me</div>
    
    <script>
    function mDown(obj) {
      obj.style.backgroundColor = "#1ec5e5";
      obj.innerHTML = "Release Me";
    }
    
    function mUp(obj) {
      obj.style.backgroundColor="#D94A38";
      obj.innerHTML="Thank You";
    }
    </script>
    
    </body>
    </html>

     

    More Examples

    - onmousedown and onmouseup : Change an image when a user holds down the mouse button.

    - onload : Display an alert box when the page has finished loading.

    - onfocus : Change the background-color of an input field when it gets focus.

    - Mouse Events : Change the color of an element when the cursor moves over it.

     

     

    JavaScript HTML DOM EventListener

    The addEventListener( ) method

    <p id="demo"></p>
    
    <script>
    document.getElementById("myBtn").addEventListener("click", displayDate);
    
    function displayDate() {
        document.getElementById("demo").innerHTML = Date();
    }
    </script>

    Attaches an event handler to the specified element Attaches an event handler to an element without overwriting existing event handlers You can add many event handlers to one element You can add many event handlers of the same type to one element, i.e two “click” events You can add event listeners to any DOM object not only HTML elements. i.e the window object Makes it easier to control how the event reacts to bubbling When using the addEventListener( ) method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup You can easily remove an event listener by using the removeEventListener( ) method

     

    Syntax

    element.addEventListener(event, function, useCapture);

    First parameter is the type of the event (like “click”, or “mousedown” or any other HTML DOM Event).

    Second parameter is the function we want to call when the event occurs.

    Third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.

    Note that you don’t use the “on” prefix for the event; use “click” instead of “onclick”

     

    Add an Event Handler to an Element

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript addEventListener()</h2>
    
    <p>This example uses the addEventListener() method to execute a function when a user clicks on a button.</p>
    
    <button id="myBtn">Try it</button>
    
    <script>
    document.getElementById("myBtn").addEventListener("click", myFunction);
    
    function myFunction() {
      alert ("Hello World!");
    }
    </script>
    
    /*
    아래같은 표현도 가능
    document.getElementById("myBtn").addEventListener("click", function() {
      alert("Hello World!");
    });
    */
    
    </body>
    </html>

     

    Add Many Event Handlers to the Same Element

    The addEventListener( ) method allows you to add many events to the same element, without overwriting existing events

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript addEventListener()</h2>
    
    <p>This example uses the addEventListener() method to add many events on the same button.</p>
    
    <button id="myBtn">Try it</button>
    
    <p id="demo"></p>
    
    <script>
    var x = document.getElementById("myBtn");
    x.addEventListener("mouseover", myFunction);
    x.addEventListener("click", mySecondFunction);
    x.addEventListener("mouseout", myThirdFunction);
    
    function myFunction() {
      document.getElementById("demo").innerHTML += "Moused over!<br>";
    }
    
    function mySecondFunction() {
      document.getElementById("demo").innerHTML += "Clicked!<br>";
    }
    
    function myThirdFunction() {
      document.getElementById("demo").innerHTML += "Moused out!<br>";
    }
    </script>
    
    </body>
    </html>

     

    Add an Event Handlers to the Window Object

    The addEventListener( ) method allow you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest.object

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript addEventListener()</h2>
    
    <p>This example uses the addEventListener() method on the window object.</p>
    
    <p>Try resizing this browser window to trigger the "resize" event handler.</p>
    
    <p id="demo"></p>
    
    <script>
    window.addEventListener("resize", function(){
      document.getElementById("demo").innerHTML = Math.random();
    });
    </script>
    
    </body>
    </html>

     

    Passing Parameters

    When passing parameter values, use an “anonymous function” that calls the specified function with the parameters

    <p id="demo"></p>
    
    <script>
    var p1 = 5;
    var p2 = 7;
    document.getElementById("myBtn").addEventListener("click", function() {
        myFunction(p1, p2);
    });
    
    function myFunction(a, b) {
        var result = a * b;
        document.getElementById("demo").innerHTML = result;
    }
    </script>

     

    Event Bubbling or Event Capturing?

    Two ways of event propagation in the HTML DOM, bubbling and capturing

    Event propagation is a way of defining the element order when an event occurs. If you have a element inside a element, and the user clicks on the element, which element’s “click” event should be handled first?

    - In bubbling

    The inner most element’s event is handled first and then the outer

    The element’s click event is handled first, then the element’s click event.

    - In capturing

    The outer most element’s event is handled first and then the inner

    The element’s click event will be handled first, then the element’s click event

     

     

    With the addEventListener( ) method you can specify the propagation type by using the “useCapture” parameter

    addEventListener(event, function, useCapture);

    The default value is false, which will use the bubbling propagation

    When the value is set to true, the event uses the capturing propagation

     

    The removeEventListener( ) method

    The removeEventListener( ) method removes event handlers that have been attached with the addEventListener( ) method

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    #myDIV {
      background-color: coral;
      border: 1px solid;
      padding: 50px;
      color: white;
      font-size: 20px;
    }
    </style>
    </head>
    <body>
    
    <h2>JavaScript removeEventListener()</h2>
    
    <div id="myDIV">
      <p>This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field.</p>
      <p>Click the button to remove the div's event handler.</p>
      <button onclick="removeHandler()" id="myBtn">Remove</button>
    </div>
    
    <p id="demo"></p>
    
    <script>
    document.getElementById("myDIV").addEventListener("mousemove", myFunction);
    
    function myFunction() {
      document.getElementById("demo").innerHTML = Math.random();
    }
    
    function removeHandler() {
      document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
    }
    </script>
    
    </body>
    </html>

     

     

    JavaScript Forms

    JavaScript Form Validation

    HTML form validation can be done by JavaScript

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function validateForm() {
      let x = document.forms["myForm"]["fname"].value;
      if (x == "") {
        alert("Name must be filled out");
        return false;
      }
    }
    </script>
    </head>
    <body>
    
    <h2>JavaScript Validation</h2>
    
    <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
      Name: <input type="text" name="fname">
      <input type="submit" value="Submit">
    </form>
    
    </body>
    </html>

     

    JavaScript Can Validate Numeric Input

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript Validation</h2>
    
    <p>Please input a number between 1 and 10:</p>
    
    <input id="numb">
    
    <button type="button" onclick="myFunction()">Submit</button>
    
    <p id="demo"></p>
    
    <script>
    function myFunction() {
      // Get the value of the input field with id="numb"
      let x = document.getElementById("numb").value;
      // If x is Not a Number or less than one or greater than 10
      let text;
      if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
      } else {
        text = "Input OK";
      }
      document.getElementById("demo").innerHTML = text;
    }
    </script>
    
    </body>
    </html>

     

    Automatic HTML Form Validation

    HTML form validation can be performed automatically by the browser:

     

    Data Validation

    The process of ensuring that user input is clean, correct, and useful Typical validation tasks are ◼ Has the user filled in all required fields? ◼ Has the user entered a valid date? ◼ Has the user entered text in a numeric field? Most often, the purpose of data validation is to ensure correct user input. Validation can be defined by many different methods, and deployed in many different ways Server side validation is performed by a web server, after input has been sent to the server. Client side validation is performed by a web browser, before input is sent to a web server.

     

    HTML Constraint Validation

    HTML5 introduced a new HTML validation concept called constraint validation HTML constraint validation is based on ◼ Constraint validation HTML Input Attributes ◼ Constraint validation CSS Pseudo Selectors ◼ Constraint validation DOM Properties and Methods

     

    Constraint Validation HTML Input Attributes

     

    Constraint Validation CSS Pseudo Selectors

     

     

    JavaScript HTML DOM Navigation

    You can navigate the node tree using node relationships.

     

    DOM Nodes

    According to the W3C HTML DOM standard, everything in an HTML document is a node:

    - The entire document is a document node

    - Every HTML element is an element node

    - The text inside HTML elements are text nodes

    - Every HTML attribute is an attribute node (deprecated)

    - All comments are comment nodes

     

    With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.

    New nodes can be created, and all nodes can be modified or deleted.

     

    Node Relationships

    The nodes in the node tree have a hierarchical relationship to each other.

    The terms parent, child, and sibling are used to describe the relationships.

    - In a node tree, the top node is called the root (or root node).

    - Every node has exactly one parent, except the root (which has no parent).

    - A node can have a number of children.

    - Siblings (brothers or sisters) are nodes with the same parent.

    From the HTML above you can read

    - <html> is the root node

    - <html> has no parents

    - <html> is the parent of <head> and <body>

    - <head> is the first child of <html>

    - <head> has one child : <title>

    - <title> has one child (a text node) : “DOM Tutorial”

    - <body> has two children : <h1> and <p>

    - <h1> has one child : “DOM Lesson one”

    - <p> has one child “Hello world!”

    - <h1> and <p> are siblings

     

    Navigating Between Nodes

    Node properties to navigate between nodes with JavaScript:

    - parentNode , childNodes[nodenumber] , firstChild, lastChild, nextSibling, previousSibling

     

    Child Nodes and Node Values

    A common error in DOM processing is to expect an element node to contain text

    <title id="demo">DOM Tutorial</title>

    - The element node <title> (in the example above) does not contain text

    - It contains a text node with the value “DOM Tutorial”.

     

    The value of the text node can be accessed by the node’s innerHTML property

    var myTitle = document.getElementById("demo").innerHTML;

    Accessing the innerHTML property is the same as accessing the nodeValue of the first child

    var myTitle = document.getElementById("demo").firstChild.nodeValue;

    Accessing the first child can also be done like this

    var myTitle = document.getElementById("demo").childNodes[0].nodeValue;

     

    DOM Root Nodes

    Two special properties that allow access to the full document.

    - document.body - the body of the document

    - document.documentElement - the full document

     

    The nodeName property

    Specifies the name of a node.

    - nodeName is read-only.

    - nodeName of an element node is the same as the tag name.

    - nodeName of an attribute node is the attribute name.

    - nodeName of a text node is always #text.

    - nodeName of the document node is always #document.

    Note:nodeNamealways contains the uppercase tag name of an HTML element.

     

    The nodeValue property

    Specifies the value of a node.

    - nodeValue for element nodes is null

    - nodeValue for text nodes is the text itself

    - nodeValue for attribute nodes is the attribute value

     

    The nodeType property

    Returns the type of node. nodeType is read-only. The most important node types are:

    Type 2 is deprecated in the HTML DOM (but works). It is not deprecated in the XML DOM

     

     

    JavaScript HTML DOM Elements (Nodes)

    Adding and Removing Nodes (HTML Elements)

     

    Creating New HTML Elements (Nodes)

    1. Frist, create the element (element node).

    2. Then append it to an existing element.

    <div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    </div>
    <script>
    var para = document.createElement("p");
    var node = document.createTextNode("This is new.");
    para.appendChild(node);
    var element = document.getElementById("div1");
    element.appendChild(para);
    </script>

     

    Creating New HTML Elements – insertBefore ( )

    The appendChild( ) method appended the new element as the last child of the parent. If you don’t want you can use the insertBefore( ) method

    <div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    </div>
    <script>
    var para = document.createElement("p");
    var node = document.createTextNode("This is new.");
    para.appendChild(node);
    var element = document.getElementById("div1");
    var child = document.getElementById("p1");
    element.insertBefore(para,child);
    </script>

     

    Removing Existing HTML Element

    To remove an HTML element, use the remove( ) method

    <div>
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    </div>
    <button onclick="myFunction()">Remove Element</button>
    <script>
    function myFunction() {
    var elmnt = document.getElementById("p1");
    elmnt.remove() ;
    }
    </script>

     

    Removing a Child Node

    For browsers that does not support the remove( ) method, you have to fine the parent node to remove an element

    <div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    </div>
    <script>
    var parent = document.getElementById("div1");
    var child = document.getElementById("p1");
    parent.removeChild(child);
    </script>

     

    Replacing HTML Elements

    To replace an element to the HTML DOM, use the replaceChild( ) method

    <div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    </div>
    <script>
    var parent = document.getElementById("div1");
    var child = document.getElementById("p1");
    var para = document.createElement("p");
    var node = document.createTextNode("This is new.");
    para.appendChild(node);
    parent.replaceChild(para,child);
    </script>

     

     

    JavaScript HTML DOM Collections

    The HTMLCollection Object

    The getElementsByTagName( ) method returns an HTMLCollection object An HTMLCollection object is an array-like list(collection) of HTML elements

    Note : The index starts at 0

     

    HTML HTMLCollection Length

    The length property defines the number of elements in an HTMLCollection

    The length property is useful when you want to loop through the elements in a collection

    An HTMLCollection is NOT an array!

      - An HTMLCollection may look like an array, but it is not.

      - You can loop through the list and refer to the elements with a number (just like an array).

      - However, you cannot use array methods like valueOf(), pop(), push(), or join() on an HTMLCollection

     

    The HTML DOM NodeList Object

    A NodeList object is a list (collection) of nodes extracted from a document.

    A NodeList objet is almost the same as an HTMLCollection object

    All browsers return a NodeList object for the property childNodes

    Most browsers return a NodeList object for the method querySelectorAll( )

    Note : The index starts at 0

     

    HTML DOM Node List Length

    The length property defines the number of nodes in a node list

    The length property is useful when you want to loop through the nodes in a node list

     

    The Difference Between an HTMLCollection and NodeList

    An HTMLCollection is a collection of document elements

    A NodeListis a collection of document nodes (element nodes, attribute nodes, and text nodes)

    A NodeList and an HTMLcollection is very much the same thing

    - An array-like collections (lists) of nodes

    - Have a length property that returns the number of items in the list (collection)

     

    HTMLCollection

    Can be accessed by their name, id, or index number ◼ Is always a live collection • If you add a

    • element to a list in the DOM, the list in the HTMLCollection will also change NodeList ◼ Can only be accessed by their index number ◼ Most often a static collection • If you add a
    • element to a list in the DOM, the list in NodeList will not change A node list is not an array! ◼ A node list may look like an array, but it is not. ◼ You can loop through the node list and refer to its nodes like an array. ◼ But, you cannot use Array Methods, like push(), pop(), or join() on a NodeList.

     

     

    728x90
    반응형
    LIST