One place for hosting & domains

      Traversing the Document Object Model with JavaScript


      The Document Object Model (DOM) is an interface that gives scripting languages, like JavaScript, access to a web page’s structure and content. You can learn more about the DOM and how it represents HTML in our guide
      Introduction to the DOM
      .

      The DOM is organized as a tree of objects, called nodes, that give access to everything from HTML elements to the text displayed on a web page. Understanding how to navigate and access nodes on this tree is essential to working with the DOM. This guide explains the DOM tree, how to navigate it, and how to access its nodes using JavaScript.

      Before You Begin

      The examples in this guide use a web browser’s developer tools to view the DOM and interact with a JavaScript console. To get the most out of the information in this guide, follow along in your own Chrome or Firefox browser.

      • On Chrome, refer to Google’s
        Open Chrome DevTools
        documentation to learn how to access their developer tools.
      • On Firefox, refer to Mozilla’s
        Open the Inspector
        documentation to learn how to access their developer tools.

      Most of this guide’s examples are based on an example web page created from the HTML source code displayed below. To follow along with this guide’s example,
      view the rendered example web page
      in your browser.

      File: example-page.html
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      
      <!DOCTYPE html>
      <html>
          <head>
              <title>Example Page</title>
          </head>
          <body>
              <div id="first-div" class="content-div">
                  <p>Example page content.</p>
                  <ul>
                      <li><span class="numeral-name" style="color: green;">First</span> item</li>
                      <li><span class="numeral-name" style="color: red;">Second</span> item</li>
                  </ul>
              </div>
              <div id="second-div" class="content-div">
                  <p><a href="https://loremipsum.io/">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tortor condimentum lacinia quis vel eros donec. Purus ut faucibus pulvinar elementum integer enim neque volutpat ac. Netus et malesuada fames ac turpis egestas sed tempus. Nulla posuere sollicitudin aliquam ultrices sagittis orci a scelerisque. Et netus et malesuada fames ac turpis egestas sed. Purus ut faucibus pulvinar elementum integer enim neque. <em>Amet consectetur adipiscing elit ut aliquam.</em></p>
              </div>
          </body>
      </html>

      Understanding the DOM Tree

      The DOM is organized as a tree, each branch of which is a node. Though many nodes represent HTML elements, they also represent attributes and text associated with elements.

      In the following sections, you learn more about the structure of the DOM tree. You also learn about the components used to identify nodes and sets of nodes, which is the basis for effectively accessing nodes.

      What Is the DOM Tree?

      The
      document object
      is the base of all of the DOM’s nodes. The nodes are arranged as a tree, with nodes nested under other nodes. Below, is an example of the DOM representation of a simple web page:

      <body>
          <div>
              <p style="color: purple;">Paragraph text</p>
          </div>
          <div>
              <ul>
                  <li>First item</li>
                  <li>Second item</li>
              </ul>
          </div>
      </body>
      

      In the example above, elements nest under other elements. The two div elements are nested under the body element. Text nodes are nested under the p and li elements, and the style attribute is considered a node under the p element, as well.

      Plotting the nesting structure out, the DOM resembles the following tree:

      body
       \_ div
       |   \_ p
       |      \_ [text]
       |      |
       |      \_ [attribute]
       \_ div
           \_ ul
               \_ li
               |   \_ [text]
               |
               \_ li
                   \_ [text]
      

      Knowing the arrangement of the DOM tree and its leaves, helps you understand how to access specific nodes when working with JavaScript. This is especially true when you are working with more complicated web pages. The
      Navigating the DOM Tree
      section of this guide includes a more in-depth discussion on moving around the nodes of the DOM tree.

      The diagram below provides a visualization of the DOM tree for this guide’s
      example web page
      . You can also view the example-page.html file in the
      Before You Begin
      section of this guide.

      A DOM tree for an example web page

      How Are Nodes Accessed?

      When working with JavaScript, you need to pinpoint a node or a particular set of nodes to access. Nodes can be identified by the three components listed below:

      • Tags, used to define HTML elements. Common examples include div for page components, p for paragraphs, and a for hyperlinks.
      • Classes that distinguish between similar elements. Classes are optional, but let you apply CSS styles and let you differentiate between a subset of the same type of element.
      • IDs, which are meant to identify particular elements. These are most useful when applied to elements that you want to be able to conveniently and consistently select individually from the DOM.

      Although this is not always the case, the arrangement of these components above generally reflects the components’ specificity, from least specific to most. For instance:

      • A tag can be used to identify every div element on a page.
      • A class can identify a smaller set of those div elements.
      • An ID can identify a specific div element.

      The
      Navigating the DOM Tree
      section below shows how these components can be used to access particular elements or set of elements.

      Query Selectors

      The popular JavaScript library
      jQuery
      introduced query selectors. These give you advanced ways to access DOM elements, using the above three components as well as attributes and other node features. Query selectors even let you combine all of these in a single command.

      JavaScript now directly implements its own query selectors as well. This gives you access to advanced DOM selections, which are covered in depth later on in this guide.

      To give you an idea, the list below includes some examples of where you can use query selectors to fetch elements. The query selectors can be based on elements:

      • matching a specific sequence of tag, class, and/or ID
      • with a given attribute and/or attribute value
      • with a matching parent element
      • that do not match a query

      Once you understand the DOM’s tree structure and how its nodes are identified, you can start using JavaScript to access and alter the DOM. The sections below show how you can use JavaScript to select specific elements from the DOM. This is divided into two sections:

      1. Using standard methods on DOM objects. These have been around for a longer time and provide some of the most straightforward selection methods.
      2. Using query selectors. These are relatively new features in standard JavaScript and provide advanced selection methods. They are ideal when you want to make complicated queries in a few commands.

      How to Access Elements via Object Methods

      Most often, you can start accessing the DOM elements you need using methods from the document object. These allow you to match elements based on tag, class, or ID.

      Moreover, these methods are inherited by any element object. This makes it possible to navigate the DOM tree from element to element, narrowing it down to the specific elements you need.

      • To fetch elements based on tag, use the getElementsByTagName method:

         document.getElementsByTagName("p");
        
      • To fetch elements based on class, use the getElementsByClassName method:

         document.getElementsByClassName("content-div");
        
      • To fetch an element based on ID, use the getElementById method:

         document.getElementById("first-div");
        

      With the exception of getElementById, all the listed methods return an array of elements, no matter how many elements actually match the query. The getElementById method only returns the first matching element, even if multiple elements on the page have the same ID.

      The following example shows how you can traverse the DOM using a combination of the inherited document object methods. It also shows how you can leverage the fact that every element inherits these methods, allowing you to narrow your search down the DOM tree.

      // Fetch the element with the `first-div` ID. This uses the `document` object,
      // so the search looks at all elements on the page.
      const first_div_element = document.getElementById("first-div");
      
      // Fetch all of the `ul` elements from under the `first-div` element. Remember,
      // this method returns an array, even if there is only one matching element.
      const ul_elements = first_div_element.getElementsByTagName("ul");
      
      // Fetch the elements with the `numeral-name` class from under the first
      // element in the array of `ul` elements.
      const numeral_elements = ul_elements[0].getElementsByClassName("numeral-name");
      
      // Grab and print the `style.color` value from each of the matching
      // `numeral-name` elements.
      for (const span_element of numeral_elements) {
          console.log(span_element.style.color);
      }
      

      If you run the above JavaScript in your web browser’s developer tools console, you see the following output.

      green
      red

      From the example above, you could also get to the numeral-name elements directly using the following code:

      const numeral_elements = document.getElementsByClassName("numeral-name");
      

      The approach of using particular elements’ methods to select lower elements on the tree can be extraordinarily helpful in some cases. For instance, if you want to select only the p elements from the second div, use the following JavaScript code:

      const second_div_element = document.getElementById("second-div");
      const p_elements = second_div_element.getElementsByTagName("p");
      

      How to Access Elements via Query Selectors

      Query selectors give you more advanced options for selecting elements from the DOM. They can be accessed via two methods from the document object — and they are also inherited on all other element objects. The two methods are the following:

      • querySelector fetches one element matching the query string. If multiple elements match, the method only returns the first one.
      • querySelectorAll fetches an array of elements matching the query string. Even if only one element matches, the result is an array.

      Like the methods covered in the previous section, these query selector methods let you select elements based on tag, class, and ID. However, the query selector syntax also lets you combine element selectors, and expands on how you can search for specific elements.

      The following examples display some key ways in which you can use query selectors to navigate and access elements from the DOM.

      • You can look for elements with a specific combination of tag, class, and ID. For instance, to search for a combination of the div tag, the content-div class, and the first-div ID, use the following code:

          document.querySelectorAll("div.content-div#first-div");
        

        The query selector syntax uses . to precede class names and # to precede IDs. It assumes labels without a prefix to be tag names.

      • You can look for elements nested under particular elements. These are called the descendants of an element. The following example finds em elements nested somewhere under any element with the content-div class:

          document.querySelectorAll(".content-div em");
        
      • You can look for elements based on associated attributes. The example below accesses the first element with an href attribute:

          document.querySelector("[href]");
        

        Alongside this, you can also specify the tag, class, and/or ID. This allows you to narrow down the search to elements whose attribute has a specific value:

          document.querySelector("a[href="https://loremipsum.io/"]");
        
      • You can look for elements based on their direct parent elements. The next command fetches all p elements that are immediate children of any div elements with the first-div ID:

          document.querySelectorAll("div#first-div > p");
        

        This selector is more specific than the descendant selector above. Where the descendant selector div em grabs an element from the example page, the child selector div > em does not.

        Why is this? The page’s em element is a direct child of a p element — that is, nested immediately under a p element — but not a div element. It is only a descendant of a div element, meaning it is nested somewhere, however deeply, beneath one.

      • You can look for elements that do not have a certain matching quality. For instance, the example below gets all p elements that are not a child of an element with the first-div ID:

          document.querySelectorAll("p:not(#first-div > p)")
        

      The above is, in fact, just a selection of some of the most commonly used features of the query selector. You can get more examples of query selector options in the
      More Information
      section of this guide.

      Conclusion

      This tutorial walked you through what the DOM tree looks like, how to navigate its parts, and how to start accessing them. The
      links below
      give you some resources to learn more about navigating the DOM, with more examples and coverage of advanced options and scenarios.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      Application Security Testing Tools


      Application security testing tools help you build applications that are less vulnerable to attacks by automating security testing, and by verifying your applications are secured against known vulnerabilities.

      In this guide, you learn what application security testing is; why you need application security tools; what types of tools exist; and what best practices your organization can use in deploying them.

      What Is Application Security Testing?

      Application Security Testing (AST) is the process of making code more resistant to attack by verifying the absence of known vulnerabilities. Applying security testing practices to all areas of your application’s stack and software development life-cycle can decrease the risk of an incident. Security testing began with manual source code reviews, but that’s no longer feasible in most cases.

      Automated testing with AST tools is a necessity today, for several reasons. These include the complexity of applications, especially web-based and mobile software; the frequent use of third-party components; time-to-market pressures; and the seemingly infinite universe of known attacks.

      The Importance of Security Testing

      You can never completely eliminate risk for your application, but you can use AST tools to greatly reduce that risk. It’s much less difficult and less expensive to detect and fix security flaws early in the development cycle than it is in production.

      Security testing tools also keep you current because they’re regularly updated to check for the latest known vulnerabilities. This is especially important considering that
      2021 saw a record number of zero-day vulnerabilities
      .

      Compared with time consuming code reviews and conventional unit and system test, AST tools provide much more speed and convenience. AST tools also classify and triage test results, helping you quickly identify the most serious vulnerabilities.

      Because they automate testing, software security tools scale well, and ensure repeatable results. AST tools also extend the breadth of security coverage by checking for new classes of vulnerabilities you previously might not have considered. Depending on your industry, there may be cases where you must perform security testing for regulatory and compliance reasons. And perhaps most important of all, AST tools help you think the way attackers do.

      Unlike source code reviews, AST tools work at every stage of an application’s lifecycle. This extends security testing throughout your organization, regardless of whether you’re on a development, devops, or IT management team.

      Types of Application Security Testing

      Static Application Security Testing

      Static application security testing (SAST) tools examine code to detect possible vulnerabilities. SAST tools are a form of white-box testing. In the white-box model, a test tool has access to all aspects of an application’s structure, including its architecture and source code. Armed with this inside knowledge, SAST tools can spot design flaws, identify logic problems, and verify code correctness. These tools optionally may perform negative testing as well, offering illegal values to test input validation and exception handling.

      SAST tools run automated scanning of source code, byte code, or compiled binaries, or some combination of these. The central tenet of all SAST tools is that they examine code at rest. Because SAST tools use a white-box model, they can analyze virtually any aspect of software, including individual functions, classes, and entire applications.

      Most AST tools, including SAST products, compare code against libraries of known vulnerabilities such as the
      Common Vulnerability and Exposures (CVE) list
      or
      VulnDB
      . A SAST tool that checks for vulnerabilities in this way might search for coding errors that could lead to privilege escalation, memory leaks, buffer overflows, and other faults.

      Example SAST products include
      AppScan Source
      ,
      Checkmarx SAST
      ,
      Coverity SAST
      ,
      Klocwork
      , and the open-source
      Insider
      and
      LGMT
      projects.

      Dynamic Application Security Testing

      Dynamic application security testing (DAST) tools examine applications while they’re running. In contrast to SAST tools, DAST takes a “black-box” approach, where the test tool has no visibility into application architecture or coding. Instead, DAST tools must discover vulnerabilities through externally observable means.

      One popular technique employed by DAST tools is the use of fuzzing. This is the practice of deliberately providing software with unexpected or illegal values, often at high rates and/or in high volumes.

      Consider the example of network routing software. A fuzzing tool might bombard routing software with illegal and constantly iterating values for every field in the
      IP header of every packet
      . Fuzzing tests often expose memory leaks or trigger hangs and reboots. They represent an excellent way to detect problems relatively early in development.

      Examples of DAST tools include
      Acunetix
      ,
      AppSider
      ,
      CheckMarx AST
      ,
      GitLab
      ,
      InsightAppSec
      ,
      Stackhawk
      , and
      Veracode
      .

      As with SAST tools, most DAST products check software integrity against a known set of vulnerabilities and exposures. An interesting, but less common, method is to use a so-called anomaly-based approach, where a test tool monitors application traffic to determine a normal baseline, and then logs behavior outside that baseline.

      Project Ava
      represents an example of the anomaly-based approach.

      While DAST tools work with any type of software, a subset of tools focuses on web application testing. These tools may use some combination of SQL injection (described in detail below), spoofing, cross-site scripting attacks, URL manipulation, password cracking, and other web-specific vulnerabilities.

      Example products include
      Detectify
      ,
      Invicti
      ,
      Nessus
      ,
      Portswigger
      , and the
      OWASP Zed Attack Proxy (ZAP)
      .

      SQL Injection Testing

      SQL injection test tools exist as a standalone category because injection attacks are so common, especially against web-based applications. SQL injection attacks work by inserting, or “injecting”, data into SQL queries to compromise a target database.

      For example, a successful SQL injection attack modifies a database by adding, updating, or deleting fields. It may expose personally identifiable information (PII) such as credit-card numbers or medical records. In some cases, SQL injection attacks also send commands to the underlying operating system.

      Because SQL injection attacks are so common, numerous tools exist to automate testing of this class of vulnerabilities. Some examples include
      SQLMap
      ,
      jSQL Injection
      , and
      BBQSQL
      . Another open-source tool,
      NoSQLMap
      , automates testing of code-injection vulnerabilities in NoSQL databases such as
      CouchDB
      and
      MongoDB
      .

      Software Composition Analysis

      Software composition analysis (SCA) tools examine every component and library used by an application, including third-party software. SCA test tools help detect problems in the open-source components or libraries found in the vast majority of networked applications.

      SCA testing uses a hybrid of SAST and DAST approaches. One caveat with SCA tools (and indeed, with any AST tool that uses a set of known vulnerabilities) is that they cannot detect problems they don’t know about. For example, SCA tools cannot detect problems in proprietary libraries developed in-house. Still, SCA tools are invaluable not only to identify vulnerabilities but also for risk management and license compliance needs.

      Vendors of SCA tools include
      Contrast Security
      ,
      Fossa
      , and
      Revenera
      .

      Mobile application Security Testing

      As the name suggests, mobile application security testing (MAST) tools look specifically for vulnerabilities in software built for mobile devices. Attackers may target a mobile device’s operating system, or its applications, or both. Some tools focus on apps on mobile devices, while others test back-end services such as cloud platforms and databases.

      Some examples of MAST tools include
      Fortify on Demand
      ,
      NowSecure
      , and the open-source
      MobSF
      project.

      Runtime Application Self-Protection

      Runtime application self-protection (RASP) tools work in production settings by analyzing application traffic and user behavior. RASP uses a hybrid of SAST and DAST approaches, analyzing both source code and live binaries to identify attacks as they happen, and block attacks in real time. For example, a RASP tool may identify an attack that targets a specific API, and then block access to that API. RASP tools also log attempted exploits to external security event and information management (SIEM) systems, allowing for real-time notification.

      Example products include
      Fortify
      ,
      Imperva
      ,
      Signal Sciences
      , and
      Sqreen
      .

      Security Testing Best Practices

      The list below includes five ways that you can make optimal use of AST tools.

      • Shift left. Even with modern software development practices, it’s still common for security testing to begin well after initial coding starts. This is often due to development and test teams working in separate silos. It’s far safer and more efficient to integrate security testing into every development phase – that is, to shift left on project timelines. By shifting left you can reduce bug count, increase code quality, and lessen the chance of discovering critical issues later on during deployment. Security testers should be involved in initial planning, and should be an integral part of any development plan.

      • Don’t trust third-party code. Virtually all networked applications today include third-party components.
        As a famous comic wryly observed
        , modern infrastructure today might well depend on, “a project some random person in Nebraska has been thanklessly maintaining since 2003.” There are many excellent third-party components available, but the onus is on development teams to ensure any outsourced code is free from known vulnerabilities and kept up to date. SCA tools should be an essential part of any AST toolkit.

      • Integrate patch management into CI/CD processes. With the proliferation of zero-day vulnerabilities, it’s no longer sufficient to task IT managers with patch management, the practice of continually updating software to guard against newly discovered attack vectors in software. Certainly patch management is important in production settings, but it’s also critical in earlier stages of the software lifecycle.
        Continuous development and integration (CI/CD)
        teams need to include patching as part of their development processes, and ensure vulnerabilities are mitigated as soon as they’re discovered. This is particularly true when incorporating third-party components such as open-source libraries; those also need to be patched as soon as those projects announce fixes for known vulnerabilities.

      • Think negative thoughts. Especially in early-stage unit testing, it’s all too common to design tests that merely verify a component works as intended. Attackers don’t think this way, and neither should developers. Negative testing – presenting applications with unexpected values – should be part of every test plan.

      • Use all the tools. Information security depends on defense in depth, the concept of employing multiple safeguards to ensure no one component’s failure leads to compromise. In an AST context, this means integrating multiple types of security testing tools into the development process. As aforementioned, there are a wide variety of tools available. Developers, devops teams, and IT managers can greatly improve code security by learning to use these tools, and by implementing them through the application lifecycle.

      Conclusion

      To reduce the risk of malicious attacks on your applications, it’s important to use application security testing tools to mitigate any vulnerabilities. This guide covered some of the most important areas of AST, like static application security testing, dynamic application security testing, and SQL injecting testing. These areas help cover security throughout an application’s technology stack and the software development lifecycle. See the
      security basics
      section our documentation library to learn more about security best practices in information technology.



      Source link

      Manipulating the DOM with JavaScript


      The Document Object Model (DOM) is a programming interface for HTML web pages. Scripting languages, like JavaScript, can access and manipulate the DOM to alter the display of a web page. In this guide, you learn about the methods and properties you can use to modify the DOM by adding and removing element nodes. You also learn how to use specialized properties to assign and update a DOM element’s CSS styles.

      If you are not familiar with the DOM, refer to our
      An Introduction to the Document Object Model (DOM)
      and
      Traversing the Document Object Model with JavaScript
      guides before continuing with this guide.

      Before You Begin

      To follow along with the examples in this guide, use your web browser’s developer tools JavaScript console to interact with the DOM.

      • On Chrome, refer to Google’s
        Open Chrome DevTools
        documentation to learn how to access their developer tools.
      • On Firefox, refer to Mozilla’s
        Open the Inspector
        documentation to learn how to access their developer tools.

      Most of this guide’s examples are based on an example web page created from the HTML source code displayed below. To follow along with this guide’s examples,
      view the rendered example web page
      in your browser as you read through the guide.

      File: example-page.html
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      
      <!DOCTYPE html>
      <html>
          <head>
              <title>Example Page</title>
          </head>
          <body>
              <div id="first-div" class="content-div">
                  <p>Example page content.</p>
                  <ul>
                      <li><span class="numeral-name" style="color: green;">First</span> item</li>
                      <li><span class="numeral-name" style="color: red;">Second</span> item</li>
                  </ul>
              </div>
              <div id="second-div" class="content-div">
                  <p><a href="https://loremipsum.io/">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tortor condimentum lacinia quis vel eros donec. Purus ut faucibus pulvinar elementum integer enim neque volutpat ac. Netus et malesuada fames ac turpis egestas sed tempus. Nulla posuere sollicitudin aliquam ultrices sagittis orci a scelerisque. Et netus et malesuada fames ac turpis egestas sed. Purus ut faucibus pulvinar elementum integer enim neque. <em>Amet consectetur adipiscing elit ut aliquam.</em></p>
              </div>
          </body>
      </html>

      How to Create and Remove DOM Elements

      To make a web page dynamic, you use JavaScript to alter the elements that make up the web page’s DOM. Typically, the DOM is altered by programmatically creating new HTML elements or moving specific elements or attributes.

      The sections below show you how to use JavaScript to create and remove elements from the DOM. You also learn how to control the way in which new elements are added to the DOM using a few specialized JavaScript methods.

      Creating Element Nodes

      The DOM represents the elements and content of an HTML document as nodes and objects. You can create element nodes in the following two ways:

      • Using a document object method to create the element and to append the new node
      • Changing the value of the innerHTML property on a parent node

      Depending on what you are trying to achieve, you might choose one approach over another. The following sections provide examples for each approach and information on when to use them.

      Using the createElement() Method

      The document object has several built-in methods for creating new nodes, like the createElement() method. This method is especially convenient when you want to create multiple elements or are working programmatically with numerous elements.

      The list below includes an overview of the steps used when creating a new element using JavaScript.

      • The createElement() method accepts the tag name of the element to create as a parameter. It creates the specified tag without any content contained within the tag.
      • Once you’ve created a new element, you have access to properties or additional methods of the element object that can be used to style the element, populate it with text, and achieve many other enhancements. The
        How to Modify Element Attributes
        discusses these changes in greater depth.
      • When your new element looks and behaves the way you intend, you can add the element node to the DOM’s target parent node. For example, you can use the appendChild() method to achieve this. The
        Inserting Element Nodes
        discusses appendChild() and other methods you can use to insert an element into the DOM.

      The example below demonstrates the steps used to create and add a new element to the DOM using the createElement() method. You can run the JavaScript code on the
      example page
      using your browser’s developer console. The JavaScript code creates a new li element and a new span element. After adding some styling and text to these new elements, the commands append the elements as children of the existing ul element.

      // Creates the new span element, assigns its class, sets its
      // color, and finally gives the element some text content
      const new_span_element = document.createElement("span");
      new_span_element.classList.add("numeral-name");
      new_span_element.style.color = "yellow";
      new_span_element.textContent = "Third";
      
      // Creates the new li element, adds the span element to it,
      // and adds some additional text content.
      const new_li_element = document.createElement("li");
      new_li_element.appendChild(new_span_element);
      new_li_element.append("item");
      
      // Appends the new li element to the existing ul element,
      // which adds the new elements to the visible DOM.
      const ul_element = document.getElementsByTagName("ul")[0]
      ul_element.appendChild(new_li_element);
      

      The result of executing the JavaScript on the
      example page
      resembles the following:

      Elements added to the example page

      Using the innerHTML Property

      You can use the innerHTML property to add HTML elements to the DOM. This property is available on the document object and any element object that is a part of the DOM.

      The innerHTML property stores a string representation of the DOM’s HTML. This means that you can use this property to overwrite existing content, create entirely new content, or manipulate content using string manipulation.

      However, the innerHTML property does not give you convenient means for modifying child elements and nodes, since it represents everything in one, often long, string.

      For this reason, the innerHTML property is useful when you need to make large and sweeping changes to several elements. It is not as useful when you want to create child elements systematically, or when you want to do so in an iterative loop.

      The example below demonstrates the typical steps used to create and add a new element to the DOM using the innerHTML property.
      You can run the JavaScript code on the
      example page
      using your browser’s developer console. The JavaScript creates a new ul element and child li elements, each with its own containing text.

      // Fetches the second-div element, then extends its innerHTML with a new
      // ul element. Observe that this requires rewriting the innerHTML.
      const second_div_element = document.getElementById("second-div");
      second_div_element.innerHTML = second_div_element.innerHTML + "<ul></ul>";
      
      // Fetches the new ul element and writes two new li elements to its
      // innerHTML, complete with classes, attributes, and text content.
      const second_ul_element = document.querySelector("#second-div > ul");
      second_ul_element.innerHTML = `<li><span class="numeral-name" style="color: red;">First</span> item</li>
      <li><span class="numeral-name" style="color: green;">Second</span> item</li>`
      

      The result of executing the above JavaScript commands on the
      example page
      resembles the following:

      Elements added to the example page via the innerHTML property

      On its own, using the innerHTML property to add new elements to the DOM can result in verbose code. Thus, even when you need to use the innerHTML property, it works best when combined with element creation methods, like createElement().

      The example below uses both the innerHTML property and the createElement() method to achieve the same results as the previous example, with much less code.

      // Adds the new ul element to the second-div element.
      const new_ul_element = document.createElement("ul");
      document.getElementById("second-div").appendChild(new_ul_element);
      
      // Writes the two new li elements to the new ul element.
      new_ul_element.innerHTML = `<li><span class="numeral-name" style="color: red;">First</span> item</li>
      <li><span class="numeral-name" style="color: green;">Second</span> item</li>`
      

      Removing Element Nodes

      There are two methods available to remove an element from the DOM: the remove() method and the removeChild() method. The remove() method completely removes the selected element node from the DOM, while the removeChild() method removes the child node of the selected element node.

      • Each element within the DOM has a remove() method that allows you to remove the element node from the DOM. For instance, using the HTML from the
        example page
        , the code below removes the em element from the p element in the second-div:

          const second_div_em_element = document.querySelector("#second-div em");
          second_div_em_element.remove();
        

        Removed element from the example page

      • The document object and each element have a removeChild() method. This lets you specify a child node that you want to remove. For instance, the code below removes the first li element from the ul element contained within the first-div:

          const first_div_ul_element = document.querySelector("#first-div > ul");
          const first_ul_li_element = first_div_ul_element.getElementsByTagName("li")[0];
          first_div_ul_element.removeChild(first_ul_li_element);
        

        Removed child element from the example page

      Inserting Element Nodes

      Before a new element is displayed on a web page, it must be explicitly added to the DOM. In the
      Using the createElement() Method
      section, this was achieved using the appendChild() method. There are, in fact, two more methods you can use to add an element to the DOM: the insertBefore() and the replaceChild() methods. These two methods let you specify where to insert an element, giving you finer control over modifying the DOM.

      Below, you can find examples that use each method to insert an element node into the DOM. Each example modifies the HTML displayed below.

      <ul>
          <li id="first-item">First item</li>
          <li id="second-item">Second item</li>
      </ul>
      

      The JavaScript below assigns the <ul> element and its contents to the ul_element variable.

      const ul_element = document.getElementsByTagName("ul")[0];
      

      Each example uses the ul_element variable.

      • The appendChild() method adds a new node to the end of the designated parent node. For example, the code below adds a third <il> element to the existing <ul> element.

          const third_li_element = document.createElement("li");
          third_li_element.textContent = "Third item";
        
          ul_element.appendChild(third_li_element);
        
      • The insertBefore() method adds the new node before an existing node. The inserted node becomes the child of the targeted parent node. This next example adds an item to the ul_element before the first-item element.

          const zero_li_element = document.createElement("li");
          zero_li_element.textContent = "Zero item";
        
          const first_li_element = ul_element.querySelector("#first-item");
        
          ul_element.insertBefore(zero_li_element, first_li_element);
        
      • The replaceChild() method replaces an existing child node with a new child node. You can see this here with the zero_li_element created above being replaced with a new item:

          const not_first_li_element = document.createElement("li");
          not_first_li_element.textContent = "First negative item";
        
          ul_element.replaceChild(not_first_li_element, zero_li_element);
        

      After running, in sequence, all the JavaScript examples from this section, your HTML should have been updated to resemble the following:

      <ul>
          <li>First negative item</li>
          <li id="first-item">First item</li>
          <li id="second-item">Second item</li>
          <li>Third item</li>
      </ul>
      

      How to Modify Element Attributes

      All HTML elements can have attributes which provide additional information about the element. In the DOM, attributes are represented as nodes and can be added to the DOM in the same way that you add element nodes. For instance, you can use the createAttribute() method to add an attribute to an element node, much in the same way that you
      use the createElement() method
      .

      The document object also has a set of specialized properties that handle the specific needs of attributes. For example, it includes some dedicated properties that deal with attributes like classes and styles. These specialized attributes are discussed below in their own dedicated sections.

      The next sections show you how to set and change an element’s attributes using the DOM’s attribute properties.

      Setting Attributes

      The setAttribute() method lets you assign an attribute’s value, whether or not it has already been set. The method is available on any element node and takes two arguments: the attribute name and its value.

      For example, using the JavaScript shown below, you can add an id attribute to the first li element of the first-div found on the
      example page
      . Use your browser’s developer console to execute the example JavaScript.

      const first_div_li_element = document.querySelector("#first-div li");
      first_div_li_element.setAttribute("id", "first-li");
      
      console.log(first_div_li_element);
      
      <li id="first-li">

      Checking for Attributes

      When you start working with element attributes, you often need to check if an element already has a value set for a given attribute. This can be achieved with the hasAttribute() method. After that, you may also need to know a given attribute’s current value. This can be done with the getAttribute() method.

      The example JavaScript below uses the hasAttribute() and the getAttribute() methods to verify that the selected <span> element has an assigned class attribute. If it does have an assigned class attribute, the browser’s developer console displays its class attribute’s value.

      const first_div_span_element = document.querySelector("#first-div span");
      if (first_div_span_element.hasAttribute("class")) {
          console.log(first_div_span_element.getAttribute("class"));
      }
      
      numeral-name

      Removing Attributes

      You can remove any existing attribute from an element object using the removeAttribute() method. The removeAttribute() method accepts the attribute to remove’s name as an argument.

      For example, use the removeAttribute() method to delete the id attribute added to the first_div_li_element in the
      Setting Attributes
      section above.

      first_div_li_element.removeAttribute("id")'
      console.log(first_div_li_element)
      
      <li>

      Styling Attributes

      Style attributes are not as straightforward to modify. This is because the single attribute, style, can actually hold numerous properties of its own. The setAttribute() method only lets you redefine the style attribute’s value, not adjust the values of its individual properties.

      For instance, you can use the setAttribute() method to assign several properties to an element’s style attribute, expressing them as a single string:

      const first_p_element = document.querySelector("#first-div > p");
      
      first_p_element.setAttribute("style", "font-weight: bold; text-align: center;");
      
      console.log(first_p_element.style);
      
      { "font-weight" → "bold", "text-align" → "center" }

      However, if you then want to adjust only one of those style properties, the setAttribute() method’s arguments are quite verbose.

      first_p_element.setAttribute("style", "font-weight: normal;");
      
      console.log(first_p_element.style);
      
      { "font-weight" → "normal" }

      To remedy this, JavaScript allows you to adjust the style attribute, and its individual properties, via the style property. This property makes available all of the CSS style properties of the style attribute, letting you set and adjust each one independently.

      Note

      While CSS hyphenates property names, JavaScript, instead, uses camelCase. So, for instance, the CSS properties font-weight and text-align become fontWeight and textAlign, respectively, in JavaScript.

      The example below accomplishes the same style changes that were attempted with the setAttribute() method in the example above:

      first_p_element.style.fontWeight = "bold";
      first_p_element.style.textAlign = "center";
      console.log(first_p_element.style);
      
      first_p_element.style.fontWeight = "normal";
      console.log(first_p_element.style);
      
      { "font-weight" → "bold", "text-align" → "center" }
      { "font-weight" → "normal", "text-align" → "center" }

      Class Attributes

      Class attributes present another special challenge when using JavaScript to modify this attribute. An element can have one or more classes, and sometimes you may find the need to work with them individually. This is especially the case with modern CSS frameworks, where you may need to check for a particular class and toggle it on or off.

      The classList property has several methods that help you modify an element’s class attribute. The property itself returns a list of the classes available to an element node.

      Checking for Classes

      You can check to see whether an element has a given class using the contains method on the classList property.

      The example below checks whether the p element in the second-div has the active class:

      const second_p_element = document.querySelector("#second-div > p");
      console.log(second_p_element.classList.contains("active"));
      
      false

      Toggling Classes

      Some classes, especially with modern CSS frameworks, require toggling for you to achieve the desired behavior for an element on a web page. For instance, the active class is often used to highlight an element. Being able to toggle the class via JavaScript could allow you to have a button that toggles highlighting on the element.

      The example below uses the second_p_element object defined in the
      Checking for Classes
      section. Recall that the element here does not have the active class assigned to it. For this reason, toggling the class adds the active class to the element.

      second_p_element.classList.toggle("active")
      console.log(second_p_element.classList.contains("active"));
      
      true

      If the element already has the class, toggling removes the class.

      second_p_element.classList.toggle("active")
      console.log(second_p_element.classList.contains("active"));
      
      false

      Adding and Removing Classes

      In some cases, you may want to permanently add or remove a class, rather than toggle it “on” and “off”. Using the toggle() method for this purpose, would first require using the contains() method to determine whether the class is already present or not.

      Instead, you can use the add() and remove() methods. These methods are straightforward and do not require any knowledge of the current classes on an element.

      The example below first adds and then removes the button class from the a element in the second-div. This is another class often used by modern CSS frameworks, usually to add an anchor link to a button’s styling.

      const a_element = document.querySelector("#second-div a");
      
      a_element.classList.add("button");
      console.log(a_element.classList);
      
      [ "button" ]
      a_element.classList.remove("button");
      console.log(a_element.classList);
      
      []

      Conclusion

      Once you understand
      what the Document Object Model is
      and are familiar with the JavaScript methods that interface with the DOM, you are ready to start manipulating DOM elements with JavaScript. This guide showed you how to use several DOM methods and properties to add and remove elements from the DOM. You also learned how to use specialized properties to assign and update a DOM element’s CSS styles.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link