Computer Science

Javascript DOM Manipulation

JavaScript DOM manipulation refers to the process of dynamically changing the structure, content, and style of a web page using JavaScript. It involves accessing and modifying the Document Object Model (DOM) of the webpage, allowing developers to add, remove, or modify elements and their attributes. This enables interactive and responsive user interfaces on web applications.

Written by Perlego with AI-assistance

11 Key excerpts on "Javascript DOM Manipulation"

  • Book cover image for: Beginning JavaScript
    • Jeremy McPeak(Author)
    • 2015(Publication Date)
    • Wrox
      (Publisher)
    9 DOM Scripting
    WHAT YOU WILL LEARN IN THIS CHAPTER:                
    • Finding elements in the page
    • Creating and inserting elements into the page dynamically
    • Navigating the web page, travelling from one element to another
    • Changing elements’ style after they are loaded in the page
    • Animating elements by manipulating their positioning
    WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
    You can find the wrox.com code downloads for this chapter at http://www.wiley.com/go/BeginningJavaScript5E on the Download Code tab. You can also view all of the examples and related files at http://beginningjs.com .
    JavaScript’s primary role in web development is to interact with the user, to add some kind of behavior to your web page. JavaScript enables you to completely change all aspects of a web page after it’s loaded in the browser. What gives JavaScript this power over a web page is the document object model (DOM), a tree-like representation of the web page.
    The DOM is one of the most misunderstood standards set forth by the World Wide Web Consortium (W3C), a body of developers who recommend standards for browser makers and web developers to follow. The DOM gives developers a way of representing everything on a web page so that it is accessible via a common set of properties and methods in JavaScript. By everything, we mean everything. You can literally change anything on the page: the graphics, tables, forms, style, and even text itself by altering a relevant DOM property with JavaScript.
    The DOM should not be confused with the browser object model (BOM) that was introduced in Chapter 8. You’ll see the differences between the two in detail shortly. For now, though, think of the BOM as a browser-dependent representation of every feature of the browser, from the browser buttons, URL address line, and title bar to the browser window controls, as well as parts of the web page, too. The DOM, however, deals only with the contents of the browser window or web page (in other words, the HTML document). It makes the document available in such a way that any browser can use exactly the same code to access and manipulate the content of the document. To summarize, the BOM gives you access to the browser and some of the document, whereas the DOM gives you access to all of the document, but only
  • Book cover image for: Learning jQuery 3 - Fifth Edition
    • Adam Boduch, Jonathan Chaffer, Karl Swedberg(Authors)
    • 2017(Publication Date)
    • Packt Publishing
      (Publisher)

    Manipulating the DOM

    The Web experience is a partnership between web servers and web browsers. Traditionally, it has been the domain of the server to produce an HTML document that is ready for consumption by the browser. The techniques we have seen in this book have shifted this arrangement slightly, using CSS techniques to alter the appearance of the HTML document on the fly. To really flex our JavaScript muscles, though, you'll need to learn to alter the document itself.
    In this chapter, we will cover:
    • Modifying the document using the interface provided by the Document Object Model (DOM )
    • Creating elements and text on a page
    • Moving or deleting elements
    • Transforming a document by adding, removing, or modifying attributes and properties
    Passage contains an image

    Manipulating attributes and properties

    Throughout the first four chapters of this book, we have been using the .addClass() and .removeClass() methods to demonstrate how we can change the appearance of elements on a page. Although we discussed these methods informally in terms of manipulating the class attribute, jQuery actually modifies a DOM property called className. The .addClass() method creates or adds to the property, while .removeClass() deletes or shortens it. Add to these the .toggleClass() method, which alternates between adding and removing class names, and we have an efficient and robust way of handling classes. These methods are particularly helpful in that they avoid adding a class if it already exists on an element (so we don't end up with <div class="first first">, for example), and correctly handle cases where multiple classes are applied to a single element, such as <div class="first second">.
    Passage contains an image

    Non-class attributes

    We may need to access or change several other attributes or properties from time to time. For manipulating attributes such as id, rel, and href, jQuery provides the .attr() and .removeAttr() methods. These methods make changing an attribute a simple matter. In addition, jQuery lets us modify more than one attribute at a time, similar to the way we worked with multiple CSS properties using the .css() method in Chapter 4 , Styling and Animating
  • Book cover image for: Advanced JavaScript
    No longer available |Learn more

    Advanced JavaScript

    Speed up web development with the powerful features and benefits of JavaScript

    Web documents built from HTML code are represented by the Document Object Model, or DOM. The DOM is a tree-like structure built from nodes. Each node corresponds to an element in the HTML source. As programmers, we can interact with the DOM to dynamically updated web pages. We can interact with the DOM by finding, creating, removing, and updating element nodes. Combining all of these concepts allows us to create dynamic web pages that can update the view based on user interaction. This kind of functionality can be seen on nearly every website, including Amazon, Facebook, and Google.

    Exercise 21: DOM Manipulation

    Your team is building an email website. The site needs to load the user's email data from a JSON file and dynamically populate a table with the email data that's loaded. The emails are provided in the example code file. The email table should show the From , To , and Subject fields and have a row for each email. Use the emails object to build the email table in the DOM through the DOM manipulation you learned about in this chapter.
    To build an email list with JavaScript using DOM manipulation techniques, perform the following steps:
    1. Open the file called exercise from /exercises/exercise21/exercise.html.
    2. In the script tag, at the bottom of the file, write the JavaScript code (under Code , at the end of this exercise).
    3. Make a new table element (<table> ) and save it into a variable called table .
    4. Create a new scope block with curly braces ({} ).
      Create an array to hold the header types To , From , and Subject . Save the array into the variable headers.
      Create a table row element (<tr> ) and save it into the variable row. Loop through the headers array with a forEach function.
    5. Inside the callback of forEach , do the following:
      Create the table header element (<th> ) and save it into the header variable. Using appendChild() , append a new text node to header . The text node should contain the header name.
      Append the header element stored in header as a child to the table row stored in row .
    6. Append the table row stored in row as a child to the table stored in table . The output is shown in the following figure: Figure 3.6: Step 4 output
  • Book cover image for: HTML5 and CSS3, Illustrated Complete
    The most widely used programming language for modern web browsers is JavaScript , which you can use to reference and change data associated with parts of HTML documents. Writing code to accomplish this requires a standardized way of referring to the parts of a web page; this system is known as the Document Object Model (DOM) . You can think of the DOM as a hierarchical arrangement of the content of an HTML document into a tree-like structure, which is known as the DOM tree . FIGURE M-1 shows the code for a simple web page along with its corresponding DOM tree. Each item in the DOM tree—including elements, attributes, and text content—is known as a node . CASE You review the underlying concepts of the DOM in preparation for working with JavaScript. Learning Outcomes • Describe the components of the Document Object Model Note that JavaScript has a different definition of a property than CSS, and CSS properties are not considered properties of JavaScript objects. QUICK TIP TABLE M-1: Commonly used properties property refers to example classValue the value of an element’s class attribute one or more class names, separated by spaces innerHTML the content of an object, including any nested HTML tags; compatible with IE8 the text in a p element src the path and source filename for an element with an src attribute the path and filename for an image textContent the text content of an object, excluding any nested HTML tags; not compatible with IE8 the text in a p element value the current value of a form field or an object property the value of the href property for an a element © 2016 Cengage Learning Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience.
  • Book cover image for: Start Programming Using HTML, CSS, and JavaScript
    If you use JavaScript in web documents only to augment HTML with behavior, then you get what is usually called Dynamic HTML or DHTML. In such cases, JavaScript should only be used to enhance a visitor’s browsing experience. The actual content that a visitor can read, however, should by no means be dependent on JavaScript. On the other hand, if you go beyond that limitation of merely enhancing a visitor’s experience, you get what is called a web application . The HTML5 specification de-fines a whole lot of objects that allow you to perform application-like feats such as manipulating graphics or storing and retrieving data. Such sets of objects are called application programming interfaces or APIs because programmers use them for inter-acting with di ff erent (software and hardware) components. There’s simply too much of everything, so we’re not going to plunge into details. I’ll just leave you some clues at the end of this course as to which directions you can take. They are gathered in Appendix B of this book. It doesn’t matter whether you’re up to developing dynamic documents or web appli-cations—there’s one API you will constantly work with. It is called the Document Object Model API, or DOM API. Think of DOM as being an object representation of the collection of all the HTML elements and strings of text positioned on a web page. By using DOM API, the programmer can manipulate or query any element or string of text on a web page indirectly by manipulating or querying a corresponding DOM object. The fundamental object of the DOM API is the Document object, which represents whatever is displayed in the browser’s window. The Document object is a property of the Window object and can hence be accessed as a global property under the name 12.4. Scripting Documents 233 document . Maria : Has this got anything to do with the document.write() that we’ve been using? Professor : Indeed it has.
  • Book cover image for: Full Stack Web Development
    eBook - ePub

    Full Stack Web Development

    The Comprehensive Guide

    • Philip Ackermann(Author)
    • 2023(Publication Date)
    • SAP PRESS
      (Publisher)
    In addition, there is a veritable wealth of other web APIs available to you in modern browsers. As a web developer, you should at least have an overview of what APIs exist and what is possible with modern browsers. This is the only way to quickly assess whether and how certain requirements for a web application can be implemented in projects. For example, you can use web APIs to store data locally in the browser, create animations, access the file system, apply encryption algorithms, and more. In the third part of this chapter, I’ll provide a compact overview of the most important web APIs.

    7.1    Changing Web Pages Dynamically Using the DOM API

    Each time you access a web page in the browser, the browser makes a request to the server via HTTP, and the server sends HTML code back to the browser; this HTML code is parsed by the browser into its own object model that is kept in the memory. This object model is referred to as the Document Object Model (DOM ), and you can access it using JavaScript.
    Figure 7.2     Browsers Parse HTML Documents into Their Own Object Model

    7.1.1    The Document Object Model

    The DOM represents the components of a web page (i.e., the HTML elements and HTML attributes) hierarchically as a tree, the so-called DOM tree . Such a DOM tree is composed of nodes , whose hierarchical arrangement reflects the structure of a web page, as shown in Figure 7.3 . The DOM API thus defines a programming interface to access the DOM tree through a program.
    Note
    An Application Programming Interface (API ) is a programming interface that provides various objects and methods, which in turn must be present in implementations (i.e., the actual implementations of the respective interface). Implementations can differ among themselves; the important thing is that the interface is adhered to.
    The DOM API provides a set of objects (with methods) through which the content of a web page (or more generally, the content of HTML documents) can be accessed. Implementations of the DOM API exist for various programming languages (including Java, Python, and C#). However, in the following sections, we’ll focus on the implementation for JavaScript, which is implicitly available to you in every browser.
    Figure 7.3     Structure of a DOM Tree
    In Chapter 4 , you already saw that JavaScript enables you to group data together in a meaningful way in the form of objects. There, you also got to know the document object, which is available in JavaScript code that runs within a web page. This object is the entry point to the DOM API, the so-called document node , as shown in Figure 7.3
  • Book cover image for: JavaScript
    eBook - ePub

    JavaScript

    Syntax and Practices

    Using any editor, we will write and test JavaScript code to interact with the DOM and see the results on the web page. Here's what you should know about DOM. DOM stands for Document Object Model. It is a part of the browser window and is the bridge through which JavaScript interacts with HTML and CSS.
    7.9.3.1 Code Snippet-1
    /* Creating a reference to any element of HTML document. * Syntax * const REFERENCE_NAME = document.querySelector (<.class/#id>) */ // For instance, creating a reference to id 'p1' const myP1 = document.querySelector(“#p1 p”); // Reference to id 'p2' const myP2 = document.querySelector(“#p2 p”); // Try printing out into console, to see what all it holds console.log(“P1”, myP1); console.log(“P2”, myP2); // Also, lets create and array of messages (It will come handy soon.) let myMessages = [ “Hello there! Coder.”, “Hope you having an amazing day <3”, “Have patience”, “Rome wasn't built in a day:)”, ]; // Manipulating the content inside HTML element, // * Method-1 | Changing the existing content. myMessages.forEach((msg) => { // for loop iterates through every element myP1.innerHTML = msg; // of myMessages, msg is the loop variable. }); /********************* DISPLAYS INFO ************************** */ let contentInfo = document.createElement(“p”); contentInfo.innerText = “I'm overWritten content!”; contentInfo.style.backgroundColor = “pink”; myP1.appendChild(contentInfo);
  • Book cover image for: Beginning HTML and CSS
    • Rob Larsen(Author)
    • 2013(Publication Date)
    • Wrox
      (Publisher)
    To make a document more interactive, the script needs to access the contents of the document and know when the user is inter- acting with it. The script does this by interacting with the browser by using the properties, methods, and events set out in the DOM interface. The DOM represents the web page loaded into the browser using a series of objects. The main object is the document object, which in turn contains several other child objects. The DOM explains what properties of a document a script can retrieve and which ones it can alter; it also defines some methods that can be called to perform an action on the document. Accessing Values Using Dot Notation To access the properties and methods of the different objects you encounter in JavaScript, you list the objects, methods, or properties in order. Each object, property, or method is separated by a period or full-stop character; hence, this is a dot notation. For example, to access any CSS class names on the element, you would type the following: document.body.className This statement has three parts separated by periods, to get to the CSS class name: ‰ ‰ The word document indicates you are accessing the document object. ‰ ‰ The word body corresponds to the element. ‰ ‰ The className indicates that you want to access any CSS classes attached to the body. Each object has different properties, objects, and methods that you can access. You continue to see this dot notation used to access them throughout the next three chapters. Different Types of Objects You will come across several types of objects in JavaScript, each of which is responsible for a related set of functionalities. For example, the document object has methods and properties that relate to the document; the forms collection, which is part of the document object, deals with information Starting to Program with JavaScript ❘ 347 regarding forms; and so on.
  • Book cover image for: Decoding JavaScript
    eBook - ePub

    Decoding JavaScript

    A Simple Guide for the Not-so-Simple JavaScript Concepts, Libraries, Tools, and Frameworks (English Edition)

    Figure 1.12: body is added as a child of html
    The parser similarly goes through the entire HTML file, until it finds the closing tag for the html element, and creates a DOM tree that looks like the following:
    Figure 1.13: The final DOM tree
    The final DOM tree for the HTML is shown in the preceding screenshot. With the help of this DOM tree, all the elements of the HTML can now be accessed with their content and attributes stored within them. Each HTML element is now considered as an object.

    JavaScript and the DOM

    In the previous section, we understood the structure of the DOM. In this section, we will explore how JavaScript (JS ) uses the DOM to fetch elements and manipulate them.
    In HTML, you must have learnt about classes and IDs. JavaScript works on those concepts to fetch the elements. JS uses the term Document object to fetch elements. The Document object refers to the entry point for the loaded web page, which is the DOM tree. You can select elements from the DOM using the following methods:
    1. document.getElementById(id) : Using this method, JavaScript parses through the DOM tree, and finds the first element having the same ID and terminates the search. Hence, if there are multiple elements having the same ID, only the first element will be returned.
    2. document.getElementsByClassName(classnames) : In this method, JavaScript parses through the entire DOM tree and locates all elements having the class name mentioned inside the parentheses. The result is a list of elements stored in an array-like datatype called as HTMLCollection . This method can also be called only on the element and not the entire document.
    3. document.getElementsByTagName(name) : Similar to the previous method, JavaScript parses through the entire DOM, collects all the elements having the same tag-name, and stores them inside an HTMLCollection . However, this method turns the name inside the parentheses to lower-case before proceeding. So, you need to be careful about elements which are written in camelCase
  • Book cover image for: Beginning HTML and CSS
    • Rob Larsen(Author)
    • 2013(Publication Date)
    • Wrox
      (Publisher)
    The external JavaScript file is read by the browser and executed directly in the place it was inserted into the document. This is exactly equivalent to embedding the script directly in the page.
    This document.write technique is used by many third-party scripts to add advanced functionality to your web pages.
    end feature

    The Document Object Model

    As mentioned at the start of the chapter, in the context of a web page, JavaScript doesn’t do much more than enable you to perform calculations or work with basic strings. To make a document more interactive, the script needs to access the contents of the document and know when the user is interacting with it. The script does this by interacting with the browser by using the properties, methods, and events set out in the DOM interface.
    The DOM represents the web page loaded into the browser using a series of objects. The main object is the document object, which in turn contains several other child objects.
    The DOM explains what properties of a document a script can retrieve and which ones it can alter; it also defines some methods that can be called to perform an action on the document.

    Accessing Values Using Dot Notation

    To access the properties and methods of the different objects you encounter in JavaScript, you list the objects, methods, or properties in order. Each object, property, or method is separated by a period or full-stop character; hence, this is a dot notation .
    For example, to access any CSS class names on the <body> element, you would type the following:
    document.body.className This statement has three parts separated by periods, to get to the CSS class name:
    • The word document indicates you are accessing the document object.
    • The word body corresponds to the <body> element.
    • The className indicates that you want to access any CSS classes attached to the body.
    Each object has different properties, objects, and methods that you can access. You continue to see this dot notation used to access them throughout the next three chapters.

    Different Types of Objects

    You will come across several types of objects in JavaScript, each of which is responsible for a related set of functionalities. For example, the document object has methods and properties that relate to the document; the forms collection, which is part of the document
  • Book cover image for: Mastering JavaScript
    No longer available |Learn more
    HTML ) is the standard markup language that defines the presentation semantics of a web page. A web page is essentially a document. The DOM provides you with a representation of this document. The DOM also provides you with a means of storing and manipulating this document. The DOM is the programming interface of HTML and allows structural manipulation using scripting languages such as JavaScript. The DOM provides a structural representation of the document. The structure consists of nodes and objects. Nodes have properties and methods on which you can operate in order to manipulate the nodes themselves. The DOM is just a representation and not a programming construct. DOM acts as a model for DOM processing languages such as JavaScript.

    Accessing DOM elements

    Most of the time, you will be interested in accessing DOM elements to inspect their values or processing these values for some business logic. We will take a detailed look at this particular use case. Let's create a sample HTML file with the following content:
    <html> <head> <title>DOM</title> </head> <body> <p>Hello World!</p> </body> </html>
    You can save this file as sample_dom.html ; when you open this in the Google Chrome browser, you will see the web page displayed with the Hello World text displayed. Now, open Google Chrome Developer Tools by navigating to options | More Tools | Developer Tools (this route may differ on your operating system and browser version). In the Developer Tools window, you will see the DOM structure:
    Next, we will insert some JavaScript into this HTML page. We will invoke the JavaScript function when the web page is loaded. To do this, we will call a function on window.onload . You can place your script in the <script> tag located under the <head>
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.