Simple Methods for Using Document Objects in JavaScript

Simple Methods for Using Document Objects in JavaScript: To begin, first refer – working-with-document-objects

In JavaScript, the Document Object provides different ways to work with collections of items in the DOM (Document Object Model). One typical example is the getElementsByClassName() method, which provides a collection of elements with the supplied class name.

In this example, a collection of all items with the class name “content” is obtained using the getElementsByClassName(‘content’) method. The text color of each member in the collection is then changed to blue by iterating over each one using a loop.

Figure 1 – Displaying the Output of Using the Document Object Collection in JavaScript

Working with Document Object Properties:

Here’s an example that modifies the document body’s background color upon a button click:

  • Button Element: The <button> element with the id changeColorButton exists in the HTML. When this button is clicked, the backdrop color will change.
  • The variable button is defined as document.getElementById(‘changeColorButton’); By using its id, this line retrieves the button element from the HTML and assigns it to the button variable.
  • function changeColor() {…}: This function, called changeColor, modifies the document body’s background color. It is intended to be called at a later time rather than being done instantly.
  • document.body.style.backgroundColor = “lightblue”;: This line in the changeColor method accesses the document body’s (document.body) style property, which lets you adjust its CSS styles. The backdrop color is changed in this instance by setting the backgroundColor property to “lightblue”.
  • button.addEventListener(‘click’, changeColor);: This line gives the button an event listener. It watches for the button’s click event and, upon button click, invokes the changeColor function. The backdrop color change is caused by this.

Figure 2 – Displaying the Output Of Using the Document Object Properties in JavaScript

Figure 3 – Showing the Output after Changing the Color

The event listener runs the changeColor function when you click the “Change Color” button, changing the document body’s background color to light blue.

Working with Document Object Methods:

Using the several methods that the Document Object provides to interact with the HTML document is part of working with Document Object Methods in JavaScript. Using the createElement(), createTextNode(), and appendChild() methods, the following example shows how to dynamically add a new paragraph to the document upon button click:

  • There is a button with the id addParagraphButton available. This button will add a new paragraph to the document when it is clicked.
  • var button = document.getElementById(‘addParagraphButton’);: By using its id, this line retrieves the button element and sets it to the button variable.
  • function addParagraph() {…}: This function includes the reasoning needed to append a new paragraph to the file.
  • var newParagraph = document.createElement(‘p’);: A new <p> (paragraph) element is created by this line.
  • var textNode = document.createTextNode(”);: The text “This is a new paragraph.” appears in a text node that is created by this line.
  • newParagraph.appendChild(textNode);: The text node is appended to the freshly formed paragraph element by this line.
  • document.body.appendChild(newParagraph);: This line adds the new paragraph to the document’s body so that it may be shown on the page along with the text node that it contains.
  • button.addEventListener(‘click’, addParagraph);: Through this line, the button gains a click event listener. The addParagraph function is called when the button is clicked, adding a new paragraph to the document.

Figure 4 – Displaying the Output of Using the Document Object Methods in JavaScript

The addParagraph function is called by the event listener when you click the “Add Paragraph” button. This function creates a new paragraph element, adds text to it, and appends it to the body of the document.

Using the Document Object with Forms:

When working with forms, JavaScript’s Document Object is very helpful because it lets you dynamically access, edit, and validate form items. This example shows how to validate a form using the Document Object prior to submission:

  • An ID-containing form MyForm has two fields where users can enter their email address and name.
  • Validation error messages are displayed in a paragraph with the id error message.
  • var form = document.getElementById(‘myForm’);: This line assigns the form element to the variable form by obtaining it by its id.
  • form.addEventListener(‘submit’, function(event) { … });: This line adds a listener for the submit event to the form. This function is called upon form submission.
  • event.preventDefault();: This line stops the page from reloading by default when a form is submitted.
  • var name = document.getElementById(‘name’).value;: The value of the name input field is obtained by this line.
  • var email = email may be found by using document.getElementById(’email’).value;: The email input field’s value is obtained in this line.
  • Next, using the validateEmail function, the code verifies that the email is in a valid format and that the name and email fields are filled out. A notification indicating the error is shown if the validation fails.
  • An indication of success appears if the validation is successful. (At this point, in an actual application, you would normally transmit the form data to a server.)
  • function validateEmail(email) { … }: This function checks the email format using a regular expression.

Figure 5 – Displaying the Output of Using the Document Object with Forms in JavaScript

The JavaScript code will validate the inputs when you click the “Submit” button after filling out the form. There will be an error message shown if the validation is unsuccessful. A success message will appear when the time passes.

Creating Cookies:

In JavaScript, setting, getting, and checking for cookies are done using the document.cookie property. Here is a comprehensive example that shows how to read and display the cookie value when the page loads, as well as how to create a cookie when a form is submitted:

  • An ID-containing form An input field for the user’s username is included in myForm.
  • To display messages, a paragraph with the id message is given.

setCookie Function:

  • A cookie with the given name, value, and expiration date (in days) is created by this function.
  • It determines the expiration date and sets it in the cookie string if the days parameter is supplied.
  • Because the cookie has the given path(/) set, it can be accessed from anywhere on the website.

getCookie Function:

  • This function gets the value associated with a given cookie.
  • The document.cookie string is divided into separate cookies by semicolons, and each cookie is then examined to see if the given name is present.

checkCookie Function:

  • This function verifies the existence of a username cookie.
  • If so, a welcome message containing the username appears.

Form Submission:

  • For the submit event, an event listener is attached to the form.
  • The default submission behavior is prevented when the form is submitted.
  • Next, it retrieves the value entered in the username box and uses that value to set a seven-day cookie.
  • The cookie has been set, as indicated by the message that appears.

Page Load:

  • The checkCookie function is triggered when the page loads in order to determine whether a username cookie is present and, if so, to show a welcome message.

How It Works:

  • The username is stored in a cookie that is established by the JavaScript code when you submit the form and click the “Submit” button.
  • The script looks for the cookie when you refresh the page or visit it again, and if it finds it, it shows a welcome message.

Figure 6 – Displaying the Output of Creating and Reading Cookies in JavaScript

Figure 7 – Showing that the Cookies have been created

The creation and reading of cookies in JavaScript is illustrated in this example, which can be helpful in customizing the user experience on your website.

Deleting Cookies:

In JavaScript, deleting a cookie entails changing its expiration date to a previous date. This is an example of how to use JavaScript to create, read, and delete cookies:

  • An ID-containing form An input field for the user’s username is included in myForm.
  • To remove the cookie, there is a button with the id deleteCookieButton available.
  • Messages are shown in a paragraph with the id message.

setCookie Function:

  • establishes a cookie with the given name, value, and days-before-expiration.
  • It determines the expiration date and sets it in the cookie string if the day parameter is supplied.

getCookie Function:

  • obtains the value of the given cookie.
  • divides the file.semicolons to extract individual cookies from the cookie string and verify that each one has the desired name.

deleteCookie Features:

  • sets a cookie’s expiration date to a past date to delete it.
  • employs the Max-Age=-99999999 property to cause the cookie to expire right away.

checkCookie Features:

  • determines if a username cookie is present.
  • If so, the username appears in a greeting message.

Filling Out Forms:

  • For the submit event, an event listener is attached to the form.
  • The default submission behavior is prevented when the form is submitted.
  • It retrieves the value entered in the username box and uses that value to set a seven-day cookie.
  • indicates that the cookie has been set by displaying a message.

Click the Delete button.

  • The delete button now has an event listener for the click event.
  • Upon clicking the button, the username cookie is removed and a notification stating that the cookie has been removed is shown.

Loading Page:

  • The checkCookie function is triggered when the page loads in order to determine whether a username cookie is present and, if so, to show a welcome message.

Figure 8 – Displaying the Output of Deleting Cookies in JavaScript

Figure 9 – Showing that the Cookies have been Deleted

How it Works:

  • The username is stored in a cookie that is established by the JavaScript code when you submit the form and click the “Submit” button.
  • The script looks for the cookie when you refresh the page or visit it again, and if it finds it, it shows a welcome message.
  • The JavaScript code deletes the username cookie and shows a notification that the cookie has been removed when you click the “Delete Cookie” button.
Scroll to Top