One place for hosting & domains

      Understanding Cryptography’s Meaning and Function


      Cryptography is a cornerstone of modern secure communication practices. From digital signatures to disk encryption, these everyday applications of cryptography enable users of the Internet, developers, and business to keep sensitive data private. This guide provides an overview of what cryptography is, a brief history of cryptography, and the differences between symmetric asymmetric encryption.

      What Is Cryptography?

      The discipline of cryptography includes the study and practice of transforming data from its original format into an unintelligible format. The goal of cryptography is to keep information secure at rest and during its transfer. In the context of computer science, cryptography focuses on the mathematical concepts and algorithms that keep communications hidden from unauthorized viewers. There are three basic types of cryptographic algorithms that are used: secret key, public key, and hash function algorithms. Data encryption applies the principles of cryptography and refers to the method used to encode data into an unintelligible format.

      Cryptography enables cybersecurity professionals to
      secure sensitive company information
      . Well-known examples of cryptographic techniques used in cybersecurity are digital signatures, time stamping, the SSL protocol, and
      public key authentication with secure shell (SSH)
      .

      History of Cryptography

      While the use of cryptography in network communications began with the advent of computers, the origins of cryptography extends much further back into history. The earliest known use to date is in an inscription that belonged to a nobleman’s tomb in Egypt in 1900 B.C. The inscriber inserted unusual symbols in place of more common hieroglyphic symbols to transform the inscription. It is widely theorized that this behavior was not intended to hide the inscription, but to make it appear more dignified and educated. However, the original text was transformed much in the same way that cryptography seeks to transform text to keep its original meaning secret.

      Early uses of cryptography intended to hide a message date back to numerous early civilizations. Keeping information private has been a consistent need for human societies. One early stage example,
      Arthashastra
      , is a classic on statecraft written circa 350-275 BCE. It includes mentions of India’s early espionage service and the “secret writings” used to communicate with spies. Julius Caesar was known to use cryptography to communicate with his army generals in 100 BC, as did numerous other leaders with armies and wars to fight.

      According to Britannica, there
      are three distinct stages in the development of cryptography
      over time. The first is manual cryptography, the second is mechanized cryptography, and the third is digital cryptography.

      The first cipher requiring a decryption key was developed in the 16th century. It is known as the
      Vigenere cipher
      which is described as “a poly-alphabetic substitution system that uses a key and a double-entry table.”

      An example of the second stage, that is the mechanization of cryptography, is the
      Hebern rotor machine
      which was developed after electricity became available in the 18th century. It embedded a secret key on a rotating disk. Another example is the famous
      Enigma machine
      which was invented at the end of World War II. It used multiple rotors that rotated at different rates while the user typed. The key was the initial setting of the rotors.

      Cryptography was used almost exclusively for military purposes for most of its history. That changed substantially in the early 1970s when IBM customers demanded additional security when using computers. For this reason, IBM developed a cipher called
      Lucifer
      .

      As computer usage increased within government agencies, the demand for less militarized applications of cryptography increased. This began the era of digital cryptography which sought to counter the growing cybersecurity attacks. In 1973, the U.S. National Bureau of Standards (NIST) sought a block cipher to become the national standard. Lucifer was accepted and dubbed the
      Data Encryption Standard (DES)
      . However, it failed to withstand intensifying brute force attacks as computing and cyber attacks became more powerful. In response, NIST solicited a new block cipher in 1997 and received 50 submissions of possible contenders. NIST chose Rijndael in 2000 and renamed it the
      Advanced Encryption Standard (AES)
      .

      Although encryption standards exist today, cryptography continues to evolve. The cryptography of the present is anchored to computer science algorithms and mathematics, like number theory.

      Symmetric vs. Asymmetric Cryptography

      The two main forms of encryption utilized by cryptography are symmetric and asymmetric. Symmetric cryptography encrypts and decrypts with a single key. Asymmetric cryptography uses two linked keys, one public and the other private.

      Both forms of encryption are used everyday, although most computer users typically don’t notice them. They’re at work in the background every time someone uses their web browser, answers emails, submits a web form, as well as other activities.

      People tend to notice cryptography when they initiate its use or directly observe it in use. One example is when using OpenSSL key management services. Another example is when emailing an encrypted document, like an Adobe PDF file that requires a password in order for it to be opened.

      Symmetric encryption is the most widely used and the oldest form of encryption. It dates back to Julius Caesar’s cipher. Symmetric encryption uses either
      stream
      or
      block cipher
      to encrypt plain text data.

      While symmetric encryption requires the sender and recipient to use the same key, that key’s use is not limited to two people in a linear conversation. Others can also be designated recipients and use the same key. Likewise, any of the recipients can respond to the sender, plus anyone on the approved list of recipients using the same key from the initial encrypted message.

      Thus, if an unauthorized person were to gain the symmetric key, that person could see, read, copy, forward the message to new recipients, and even respond to the original group. Hackers gain access to the key either by pilfering it from a storage space on a device that hasn’t been properly secured, or by extracting it from the message itself.

      The key must be transmitted when the sender and receiver are not in the same location. It is therefore vulnerable if the network or channel are compromised and must be closely protected.

      By comparison, asymmetric cryptography uses two linked keys, one public and the other private, on each side of the conversation or transaction. Both sender and receiver have a private key in their possession alone. Each also has a public key – meaning a unique key of their own made public only by virtue of being exchanged with another person. The sender uses the recipient’s public key to encrypt the file. The recipient then uses their private key to decrypt it. Only the recipient can decrypt the file because no one else has access to that person’s private key. Asymmetric encryption also enables digital signature authentication.

      Examples of asymmetric cryptography in everyday use include
      RSA
      , the
      Digital Signature Standard (DSS/DSA)
      , and the
      TLS/SSL protocol
      .

      Both forms are considered secure, but the level of security in any given encrypted message has more to do with the size of the key(s) than the form of encryption. Just like passwords, keys must be complex, difficult to obtain, decode, or reveal.

      The Objectives of Cryptography

      Cryptography has four major goals: confidentiality, integrity, authentication, and non-repudiation. Put another way, the goals are data privacy (confidential treatment), data authenticity (verified source), and data integrity (original and unaltered message). Non-repudiation refers to the combination of each of these three things to prove undeniable validity of the message or data. One example of non-repudiation in use is a service used to authenticate digital signatures and to ensure that a person cannot reasonably deny having signed a document. Some popular examples are
      DocuSign
      and
      PandaDoc
      .

      Of these goals, confidentiality carries the most weight. The need to ensure that an unauthorized party cannot access the data is the ultimate objective of cryptography. That does not mean that the remaining goals are of less importance.

      Data integrity is vital to ensure that the message has not been altered in some way. Otherwise, the receiving party could be manipulated into taking a wrong or undesirable action. Whether a spy is sending a message to their country’s leadership, or a company is sending instructions to a field office, both sender and receiver need assurance that the message sent is identical to the message received.

      Authenticity is essential to ensure that the user or system is known and trusted. Establishing the identity of the user (sender or recipient) is the crux of this assurance. However, the system must also be known in order to
      prevent ransomware attacks
      that involve phishing (fraudulent emails), vishing (fraudulent voice mails and phone calls), smishing (fraudulent texts), and other deceptive forms of communication.

      Types of Cryptography

      There are three types of cryptography: secret key cryptography, public key cryptography, and hash functions.

      The least complicated and fastest to use is secret key cryptography, also known as symmetric cryptography. This type uses one key to encrypt and decrypt communications. It protects data at rest and data in transit, and is most often used on data at rest. The most well-known algorithms used in secret key cryptography are
      Advanced Encryption Standard (AES)
      ,
      Triple Data Encryption Standard (3DES)
      , and
      Rivest Cipher 4 (RC4)
      .

      Public key cryptography, or asymmetric cryptography, uses two keys on each end of the communication. Each pair consists of a public and a private key. Public keys are exchanged between sender and recipient. The sender then uses the recipient’s public key to encrypt the message. The recipient uses their private key to decrypt the message. Examples of public key use are plentiful in just about any communication over the Internet such as
      HTTPS
      ,
      SSH
      ,
      OpenPGP
      ,
      S/MIME
      , and a
      website’s SSL/TLS certificate
      .

      The math connecting public and private keys makes it impossible to derive the private key from the public key. However, the public key is derived from the private key, which is why private keys should never be shared.

      Hash functions are one-way functions and completely irreversible. This renders the original message unrecoverable. A hashing algorithm produces unique outputs for each input. Examples include
      SHA-256 and SHA3-256
      , both of which change any input into a new and complex 256-bit output. Bitcoin, the largest and best known of the cryptocurrencies, uses SHA-256 cryptographic hash function in its algorithm. Almost all passwords are stored securely as hashed functions which are then used to verify the correct password is being used. A hacker must try every input possible to find the exact same hash, which renders the effort useless.

      What is Cryptography in Cyber Security?

      Modern cryptography is based on mathematical theory and computer science. It continues to evolve as computing becomes more powerful. For example,
      quantum computers will break today’s encryption
      standards in the foreseeable future. Computer scientists are already hard at work developing quantum-safe algorithms and security protocols. Whatever the solutions turn out to be, they’ll be built based on the laws of physics and the rules of mathematics.

      Both now and in the future, cryptography is central to cybersecurity efforts. Whether it is protecting data points and documents across communication channels, or large data sets in transit or at rest in storage and on devices; cryptography is the first line of defense. Nothing is fool-proof, and therefore all things in cybersecurity, including cryptography, must evolve to match increasingly sophisticated threats and evermore powerful computers.

      To understand the necessity of encryption, one need only to look at the headlines. The frequency of data breaches and intercepted or leaked messages is readily apparent. In February 2022 alone, more than 5.1 million records were breached, according to research by
      IT Governance
      .

      The central assumption with cryptography is that other parties are going to try to breach data and many are going to be successful. Encryption is meant to thwart their efforts even if they succeed in reaching the data. It is an essential line of defense in cybersecurity architecture and hinders an attacker’s efforts to access sensitive information.

      Other forms of cybersecurity focus on other fronts such as protecting the network, limiting or stopping access to data, and protecting data from manipulation, i.e. deliberate corruption of meaning or readability.

      Layers of different cybersecurity methods
      work in tandem to provide a better, stronger defense. Even so, encrypting data is a primary defense used across all efforts in protecting data. Its use is of particular value to secure communications which by necessity must be shared with parties beyond secure company walls.

      Conclusion

      Cybersecurity and encryption are tasks that require research, time, and effort in order to be effective. Many companies prefer to leverage the efforts of vendor teams rather than overburden their internal cybersecurity teams to develop these additional layers of protection. However, there are many tools available to encrypt areas of your infrastructure and network. For example, you can use
      LUKS to encrypt a Linux server’s filesystem disk
      . Similarly, you can use
      GPG keys to send encrypted messages via email
      .



      Source link

      Angular Animations: Get Started


      Web animations add dynamic graphics and effects to a web page. Movement on a web page communicates information to users and adds visual interest. Animation on a web page is typically achieved by changing the state of an HTML element over time. For example, an HTML element’s color or position can change as a result of user interaction on a web page. Most popular web frameworks offer animation support that simplifies animating elements on your web pages or applications. This guide shows you how to get started creating animations using the Angular web framework.

      Setup the Angular Project

      1. Follow the steps in our
        Getting Started with Angular
        guide to install Node.js, the Node Version Manager (nvm), and Angular. As a result of following those steps, you should have a directory named example-app in your home folder.

      2. In your Angular project’s root application module, enable the animations module by importing the BrowserAnimationsModule as shown in the following code:

        File: /home/username/example-app/src/app/app.module.ts
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        
        import { NgModule } from '@angular/core';
        import { BrowserModule } from '@angular/platform-browser';
        import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
        
        @NgModule({
          imports: [
            BrowserModule,
            BrowserAnimationsModule
          ],
          declarations: [ ],
          bootstrap: [AppComponent]
        })
        export class AppModule { }
            

        The bootstrap key bootstraps the component that contains the majority of your animation code. You create this code in the next section.

      Angular Animation Example

      The example Angular code used in this guide animates the transition between two background colors contained within a <div> HTML element.

      Add Metadata to Angular Component

      In your preferred text editor, open your Angular application’s /home/username/example-app/src/app/app.component.ts file and add the animations metadata property to the declared component. The majority of the code used to animate the <div> element is contained in the animations metadata option.

      File: /home/username/example-app/src/app/app.component.ts
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css'],
        styleUrls: ['app.component.css'],
        animations: [
            //Add the animations metadata option
        ]
      })
      ...
          

      The HTML that is animated is stored in the component’s HTML template which is the ./app.component.html file. You add the HTML code to this file in the next section.

      Note

      Ensure that the top of your app.component.ts file includes the following import statements.

      File: /home/username/example-app/src/app/app.component.ts
      1
      2
      
      import { Component } from '@angular/core';
      import { trigger, state, style, animate, transition } from '@angular/animations';

      Create the Angular Component HTML Template

      Your Angular project already contains a component HTML template file. The app.component.ts component file points to the location of the ./app.component.html file in the templateURL metadata. In this section, you add the HTML to animate with Angular.

      1. Open your Angular project’s /home/username/example-app/src/app/app.component.html file and delete all of the example boilerplate code.

      2. Add the example HTML template code as shown below:

        File: /home/username/example-app/src/app/app.component.html
        1
        2
        3
        4
        5
        6
        7
        
        <h1>Angular Animation Example</h1>
        
        <div (click)="changeState()" [@changeDivColor]=currentState >
          <h2>A Heading Contained in a Div</h2>
          <p>Click inside the Div to view the div's background color change using an Angular animation.</p>
        </div>
            

        The HTML template adds a <div> element that gets animated. For now, the <div> does not call any of the functionality that enables the <div> to be animated. You add this in the next section.

      3. Run the Angular local server with the following command:

         ng serve
        
      4. Navigate to http://localhost:4200 in a browser window and you should see the rendered HTML.

      Add an Angular Animation Trigger

      In this section, you add an Angular animation trigger. The trigger is used to bind the animation code and behavior to the HTML element that you want to animate. The animation trigger contains the animation states that define the div’s background color state change.

      Open the component file and add the trigger() function to the animations metadata object.

      File: /home/username/example-app/src/app/app.component.ts
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      
      @Component({
        selector: 'app-root',
        templateUrl: './div-animation.component.html',
        styleUrls: ['./app.component.css'],
        animations: [
          trigger('changeDivColor', [
              //Animation states are added here.
          ])
        ]
      })
      ...
          

      In the example above, changeDivColor is the animation trigger. This trigger can now be called in your Angular component template. You complete that step in one of the following sections. The next section shows you how to add animation states to your component.

      Add Angular Animation States

      Angular animation states specify the change that you want to apply during your animation. For the example, the <div> background color’s state should change from one color to another. You use Angular’s state() function to name the state and define the element’s CSS styles that are associated with the state.

      Open the component file and add the two state() functions to the changeDivColor state of the trigger() function as shown below:

      File: /home/username/example-app/src/app/app.component.ts
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      
      @Component({
        selector: 'app-root',
        templateUrl: './div-animation.component.html',
        styleUrls: ['./app.component.css'],
        animations: [
          trigger('changeDivColor', [
            state('start', style({
              border: '5px outset blue',
              backgroundColor: 'green',
              textAlign: 'center'
            })),
            state('end', style({
              border: '5px outset blue',
              backgroundColor: 'lightgreen',
              textAlign: 'center'
            })),
          ])
        ]
      })
      ...
          

      The state functions assign a name to each state and provide their associated styles. The start state uses a background color of green, while the end state uses a background color of light green.

      Add Angular Animation Transitions

      Now, you need to define the Angular animation’s transitions from one state to another. To do this, you use the transition() function.

      Open the component file and add the transition() function to the end of the trigger() function as shown below:

      File: /home/username/example-app/src/app/app.component.ts
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      
      ...
      @Component({
        selector: 'app-root',
        templateUrl: './div-animation.component.html',
        styleUrls: ['./app.component.css'],
        animations: [
          trigger('changeDivColor', [
            state('start', style({
              border: '5px outset blue',
              backgroundColor: 'green',
              textAlign: 'center'
            })),
            state('end', style({
              border: '5px outset blue',
              backgroundColor: 'lightgreen',
              textAlign: 'center'
            })),
            transition('start <=> end', animate('1000ms'))
          ])
        ]
      })
      ...
          

      The updated code above creates a state-to-state transition. The first state transition goes from the start state to the end state, while the second transition does the opposite. This state transition allows you to toggle between both states each time a user clicks on the bound HTML element (the <div> element). The transition() function uses the animate() function to specify the timing for the transition.

      Add the Toggle Function

      Now that your animation is defined, you need to add a function that can detect the <div> state and toggle between the two states.

      Add the following toggleState() function to your AppComponent class. The AppComponent class is located below the @Component decorator.

      File: /home/username/example-app/src/app/app.component.ts
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      
      ...
      export class AppComponent {
        title = 'example-app';
      
        divState = 'start';
      
        toggleState() {
          this.divState = this.divState === 'start' ? 'end' : 'start';
        }
      }
          

      The code above adds a divState variable that stores the current toggle state of the <div>. The toggleState() function uses a conditional ternary operator to update the value of divState depending on its current value.

      Now that your animation code and toggle functionality is in place, you need to update the Angular HTML template to bind everything together. You complete this in the next section.

      Bind the Animation Trigger to the HTML Component Template

      In this section, you bind the animation trigger you created in the previous steps to the <div> element.

      1. Open your HTML component template and add the animation trigger to the <div>. You also add a click event that invokes the toggleState() function you added to the AppComponent class declaration.

        File: /home/username/example-app/src/app/app.component.html
        1
        2
        3
        4
        5
        6
        7
        
        <h1>The div element</h1>
        
        <div (click)="toggleState()" [@changeDivColor]=divState>
          <h2>This is a heading in a div element</h2>
          <p>This is some text in a div element.</p>
        </div>
            

        Notice that the @changeDivColor trigger binding is set to the value of the divState variable. This enables the div to begin in the start toggle state. You are now ready to view your animation.

      2. Navigate to http://localhost:4200 in a browser window and you should see the rendered HTML.

        Angular rendered green HTML div.

        Click inside the <div> container and you should see the animated background color transition from green to light green and vice versa, with each click.

        Angular rendered light green HTML div.

      Conclusion

      This guide showed you how to use the Angular framework to get started creating animations. Angular’s
      triggers
      ,
      states
      , and
      transitions
      help you animate elements on a web page. The basic example included in this guide provides a foundation that you can use to
      create more advanced animations
      using the Angular query() and stagger() functions.

      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

      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