Table of Contents - DOM (Document Object Model)

  1. JavaScript - How to Manipulate DOM Elements?
  2. How to Add a Class to DOM Element in JavaScript?
  3. How to select DOM Elements in JavaScript?
  4. How to get all ID's of the DOM elements with JavaScript?
  5. JavaScript – How to Get the Data Attributes of an Element?
  6. How To Get Element By Class Name In JavaScript?
  7. How to Get Value by Class Name using JavaScript?
  8. How to Get Domain Name From URL in JavaScript?
  9. How to Get Protocol, Domain and Port from URL using JavaScript?
  10. How to Extract the Host Name from URL using JavaScript?
  11. How to Get the Current URL using JavaScript?
  12. How to Get URL Parameters using JavaScript?
  13. How to Parse URL using JavaScript?
  14. Manipulating HTML Elements with JavaScript
  15. How to use innerHTML in JavaScript?
  16. JavaScript innerHTML

DOM

01 JavaScript - How to Manipulate DOM Elements?

The DOM stands for the Document Object Model (DOM), which allows us to interact with the document and change its structure, style, and content. We can use the DOM to change the content and style of an HTML element by changing its properties.

We can manipulate or change the DOM elements by using the following methods:

1. Change the Content of an Element

You can change the content inside an HTML element using JavaScript. The two most common properties for this are innerHTML and textContent:

<body>
  <div id="example1">This is the original content using innerHTML.</div>
  <div id="example2">This is the original text content using textContent.</div>
  <button onclick="changeContent()">Change Content</button>
  <script>
  // Function to change content
  function changeContent() {
    document.getElementById("example1").innerHTML = 
      "This is changed using innerHTML!";
    document.getElementById("example2").textContent = 
      "This is changed using textContent!";
    }
  </script>
</body>
Change text, make bold using innerHTML.

In this example

2. Manipulate the Class Attribute

You can add, remove, or toggle classes on an element using JavaScript. This is helpful for styling or applying animations.

<html>
<head>
  <style>
    .highlight {
      color: red;
      font-weight: bold;
    }
    .bold {
      font-weight: bold;
    }
  </style>
</head>
<body>
  <div id="example" class="bold">This is a text element with the "bold" class.</div>

  <button onclick="addClass()">Add 'highlight' Class</button>
  <button onclick="removeClass()">Remove 'bold' Class</button>
  <button onclick="toggleClass()">Toggle 'highlight' Class</button>
  <script>
    function addClass() {
      document.getElementById("example").classList.add("highlight");
    }
    function removeClass() {
      document.getElementById("example").classList.remove("bold");
    }
    function toggleClass() {
      document.getElementById("example").classList.toggle("highlight");
    }
  </script>
</body>
</html>

Output:

Add highlight class, remove bold class, or toggle highlight class.

In this example

3. Set CSS Styles Using JavaScript

You can directly manipulate the CSS styles of an element using the style property. This allows you to dynamically change how elements appear on the page.

// Changing multiple CSS properties
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.fontSize = "20px";
// Adding more than one style
document.getElementById("demo").style.cssText = "color: blue; font-size: 18px;";

4. Create, Add, and Remove Elements

Sometimes, you need to create new elements, add them to the DOM, or remove existing ones. You can do this easily with the following methods;

// Create a new element
let newDiv = document.createElement("div");
newDiv.textContent = "This is a new div";
// Add the new element to the DOM
document.body.appendChild(newDiv);
// Remove an element from the DOM
document.body.removeChild(newDiv);

5. Insert Elements at a Specific Position

You can insert new elements at specific positions relative to existing elements using methods like insertBefore().

// Create a new element
let newDiv = document.createElement("div");
newDiv.textContent = "This is a new div";

// Find an existing element to insert before
let referenceNode = document.getElementById("referenceElement");

// Insert the new element before the reference element
document.body.insertBefore(newDiv, referenceNode);

6. Manipulate Element Attributes

You can easily get, set, or remove the attributes of an HTML element using the following methods:

// Get the value of an attribute
let src = document.getElementById("image").getAttribute("src");

// Set a new value for an attribute
document.getElementById("image").setAttribute("src", "new-image.jpg");

// Remove an attribute
document.getElementById("image").removeAttribute("src");

7. Manipulate Data Attributes

HTML5 introduced data attributes, which are custom attributes that you can use to store extra information about an element. These are particularly useful for adding data to an element without affecting its visual structure.

// Setting a data attribute
document.getElementById("demo").dataset.userId = "12345";
// Getting a data attribute
let userId = document.getElementById("demo").dataset.userId;
console.log(userId); // Outputs: 12345

02 How to Add a Class to DOM Element in JavaScript?

Adding a class to a DOM (Document Object Model) element in JavaScript is a fundamental task that enables developers to dynamically manipulate the appearance and behavior of web pages. Classes in HTML provide a powerful way to apply CSS styles or JavaScript functionality to multiple elements at once.

By using JavaScript, you can easily add, remove, or toggle classes on elements, making your web applications more interactive and responsive to user actions.

These are the following approaches:

Table of Content

In this approach, we are using classList property to add the class into the DOM element. It returns the class name as a DOMTokenList object. It has a method called “add” which is used to add class name to elements. We will access the div using the getElementById and we will use the add property of classList to add a class.

Syntax:

element.classList.add("className")

Example: This example shows the implementation of the above-explained approach.

<!DOCTYPE html>
<html>
<head>
  <style>
    .geek {
      background-color: green;
      font-size: 50px;
    }
  </style>
</head>
<body>
  <button onclick="myClass()">Try it</button>
  <div id="gfg">Geeks for Geeks</div>
  <script>
    function myClass() {
      let elem = document.getElementById("gfg");

      // Adding class to div element 
      elem.classList.add("geek");
    } 
  </script>
</body>
</html>

Output:

Update heading font size, background color using class.

Using className Property

In this approach, we are using the className property. This property returns the className of the element. If the element has already a class then it will simply add another one to it or else it will append our new class to it.

Syntax:

HTMLElementObject.className

Example: This example shows the implementation of the above-explained approach.

<!DOCTYPE html>
<html>
<head>
  <style>
    .geekClass {
      background-color: green;
      text-align: center;
      font-size: 50px;
    }
  </style>
</head>
<body>
  <div id="gfg">
      Geeks For Geeks
  </div>
  <button onclick="myClassName()">Add Class</button>
  <script>
    function myClassName() {
      let element = document.getElementById("gfg");
      // Adding the class geekClass to element 
      // with id gfg space is given in className 
      // (" geekClass") as if there is already 
      // a class attached to an element than our 
      // new class won't overwrite and will append 
      // one more class to the element 
      element.className += " geekClass";
    } 
  </script>
</body>
</html>

Output:

Update font size, background color using class.

03. How to select DOM Elements in JavaScript?

Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or modifying styles.

Below are the approaches to select DOM elements in JavaScript:

Table of Content

1. Using getElementById

This method selects a single element by its unique ID attribute.

Syntax:

document.getElementById('id')

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, 
    initial-scale=1.0">
  <title>getElementById Example</title>
</head>
<body>
  <h1 id="gfg">GeeksForGeeks</h1>
  <script>
  // styling the h1 tag
  const element = document.getElementById('gfg');
    element.style.color = "green";
    element.style.textAlign = "center";
    element.style.margin = "30px";
    element.style.fontSize = "30px";
  </script>
</body>
</html>

Output:

Geeks4Geeks in green.

2. Using getElementsByClassName

This method selects elements based on their class attribute. It returns a collection of elements with the specified class name.

Syntax:

document.getElementsByClassName('class')

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
    content="width=device-width, initial-scale=1.0">
  <title>getElementsByClassName Example</title>
</head>
<body>
  <h1 class="selector">GeeksForGeeks</h1>
  <h2 class="selector">DOM selector in JavaScript</h2>
  <script>
    const elements = 
      documSizeent.getElementsByClassName('selector');
      elements[0].style.color = "green";
      elements[1].style.color = "red";
      elements[0].style.textAlign = "center";
      elements[1].style.textAlign = "center";
      elements[0].style.marginTop = "60px";
  </script>
</body>
</html>

Output:

Geeks4Geeks in green, DOM select in JavaScript in red.

03. Using getElementsByTagName

This method selects elements based on their tag name. It returns a collection of elements with the specified tag name.

Syntax:

document.getElementsByTagName('tag')

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
    content="width=device-width, initial-scale=1.0">
  <title>getElementsByTagName Example</title>
</head>
<body>
  <p>Thanks for visiting GFG</p>
  <p>This is showing how to select DOM element using tag name</p>
  <script>
    const paragraphs = document.getElementsByTagName('p');
      paragraphs[0].style.color = "green";
      paragraphs[1].style.color = "blue";
      paragraphs[0].style.fontSize = "25px";
      paragraphs[0].style.textAlign = "center";
      paragraphs[1].style.textAlign = "center";
      paragraphs[0].style.marginTop = "60px";
  </script>
</body>
</html>

Output:

1st paragraph in green, 2nd in blue, all centered, 1st paragraph 60px from top of form.

04. Using querySelector

This method selects the first element that matches a specified CSS selector. It returns only one element.

Syntax:

document.querySelector('selector')

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
    content="width=device-width,
      initial-scale=1.0">
  <title>querySelector Example</title>
</head>
<body>
  <div class="gfg">GeeksForGeeks</div>

  <script>
    const element = 
      document.querySelector('.gfg');
      element.style.color = "green";
      element.style.textAlign = "center";
      element.style.margin = "30px";
      element.style.fontSize = "30px";
  </script>
</body>
  
</html>

Output:

Geeks4Geeks in green, centered, 30px from margin, 30px in size.

05. Using querySelectorAll

Similar to querySelector, but it returns a NodeList containing all elements that match the specified CSS selector.

Syntax:

document.querySelectorAll('selector')

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
    content="width=device-width, initial-scale=1.0">
  <title>querySelectorAll Example</title>
</head>
<body>
  <h1 class="selector">GeeksForGeeks</h1>
  <p class="selector">
    This is showing how to select DOM element
    using tag name
  </p>
  <script>
    const elements = document.querySelectorAll('.selector');
      elements[0].style.color = "green";
      elements[1].style.color = "red";
      elements[0].style.textAlign = "center";
      elements[1].style.textAlign = "center";
      elements[0].style.marginTop = "60px";
  </script>
</body>
</html>

Output:

How to select dom element using tag name.

04. How to get all ID of the DOM elements with JavaScript?

Given a HTML document and the task is to get the all ID of the DOM elements in an array. There are two methods to solve this problem which are discusses below:

Approach 1:

First select all elements using $(‘*’) selector, which selects every element of the document. Use .each() method to traverse all elements and check if it has an ID. If it has an ID then push it into the array.

Example: This example implements the above approach.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>
    How to get all ID of the DOM
    elements with JavaScript ?
  </title>
  <script src=
    "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
  </script>
</head>
 
<body>
  <h1 style="color: green">
    GeeksforGeeks
  </h1>
  <p>
    Click on the button to get 
    all IDs in an array.
  </p>
  <button onclick="muFunc()">
    Click Here
  </button>
 
  <p id="GFG"></p>
   <script>
     let res = document.getElementById("GFG");
     function muFunc() {
       let ID = [];
       $("*").each(function () {
         if (this.id) {
           ID.push(this.id);
         }
       });
       res.innerHTML = ID;
     }
   </script>
</body>
</html>

Output:

Click to get all ids in array.

Approach 2:

Example: This example implements the above approach.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>
    How to get all ID of the DOM
    elements with JavaScript ?
  </title>
  <script src= 
    "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
  </script>
</head>
<body>
  <h1 style="color: green">
    GeeksforGeeks
  </h1>
  <p>
    Click on the button to get 
    all IDs in an array.
  </p>
   <button id="Geeks" onclick="muFunc()">
    Click Here
  </button>
  <p id="GFG"></p>
  <script>
    let res = document.getElementById("GFG");
    function muFunc() {
      let ID = [];
    ID = $("*").map(function() {
      if (this.id) {
        return this.id;
      }
    }).get();
    res.innerHTML = ID;
  }
  </script>
</body>
</html>

Output:

Click to get/display all ids in an array.

05. JavaScript – How to Get the Data Attributes of an Element?

Here are the various methods to get the data attributes of an element using JavaScript.

1. Using dataset Property

The dataset property in JavaScript allows you to access all data attributes of an HTML element as a DOMStringMap object. It simplifies retrieving, modifying, or interacting with custom data stored in attributes like data-id or data-name.

Syntax


const e =  document.getElementByID('demo') // Accessing the element 
const dataId  = e.dataset.dataID //Access the data-id attribute 
<!DOCTYPE html>
<html>
  
<body>
    <div
        id="element"
        data-typeId="123"
        data-name="name"
        data-points="10"
        data-important="true">
        This is the Target Element.
    </div>

    <br />
    <button onclick="myFunction()">
          Get Attributes
      </button>
    
      <p id="result"></p>

    <script>
        let result = document.getElementById("result");
        let e = document.getElementById("element");

        function myFunction() {
            let jsonData = JSON.stringify({
                id: parseInt(e.dataset.typeid),
                points: parseInt(e.dataset.points),
                important: e.dataset.important,
                dataName: e.dataset.name
            });
            result.innerHTML = jsonData;
        }
    </script>
</body>
  
</html>

Output:

Click to get/display attributes for target elements.

2. Using getAttribute() Method

The getAttribute() method in JavaScript retrieves the value of a specified attribute from an HTML element. To get data attributes, use element.getAttribute(‘data-attribute’). This method allows precise selection and manipulation of individual data attributes without accessing all at once.

<!DOCTYPE html>
<html>
  
<body>
    <div
        id="target"
        data-typeId="123"
        data-name="name"
        data-points="10"
        data-important="true"
    >
        This is the Target Element.
    </div>

    <br />
    <button onclick="myFunction()">Get Attributes</button>
    <p id="result"></p>

    <script>
        let result = document.getElementById("result");
        let e = document.getElementById("target");

        function myFunction() {
            let jsonData = JSON.stringify({
                id: parseInt(e.getAttribute('data-typeId')),
                points: parseInt(e.getAttribute('data-points')),
                important: e.getAttribute('data-important'),
                dataName: e.getAttribute('data-name')
            });
            result.innerHTML = jsonData;
        }
    </script>
</body>
  
</html>

Output:

Click to get/display attributes for target elements.

06. How To Get Element By Class Name In JavaScript?

When working with the DOM in JavaScript, selecting elements by their class names is a common task. JavaScript provides several methods to achieve this, whether we need to select one or multiple elements. In this article, we will cover different approaches to get elements by class name in JavaScript.

Prerequisites

Below are the following approaches to get elements by class name in Javascript:

Table of Content

1. Using document.getElementsByClassName()

In this approach we are using the document.getElementsByClassName() method. This method selects all elements with a specific class name and returns a live HTMLCollection. Think of it as a way to collect all elements with same label. In this, list gets updated automatically if elements are added or removed.

Syntax:

var elements = document.getElementsByClassName("className");

Example: In this example we are using the getElementsByClassName() method to get element by class name in JavaScript.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width,
    initial-scale=1.0">
  <title>Get Elements by Class Name</title>
  <style>
    .output {
      margin-top: 20px;
      padding: 10px;
      border: 1px solid #ccc;
      background-color: #f9f9f9;
    }
  </style>
</head>

<body>
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>

  <div class="output" id="output1"></div>

  <script>
    var boxes =
      document.getElementsByClassName("box");
    var output =
      document.getElementById("output1");
      output.innerHTML = 
      "Number of boxes: " + boxes.length;
  </script>
</body>

</html>

Output:

Get/display elements by class name, number of elements.

2. Using document.querySelector()

In this approach we are using the document.querySelector() method. This method returns the first element that matches the specified selector (class name). It is useful when you only need to select a single element by class name.

Syntax:

var element = document.querySelector(".className");

Example: In this example we are using the querySelector() method to get element by class name and we will change the background color of selected class in javascript.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width,'' initial-scale=1.0">
  <title>Query Selector Example</title>
  <style>
    .box {
      padding: 10px;
      margin: 5px;
      border: 1px solid #ccc;
    }
  </style>
</head>

<body>
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>

  <script>
    var firstBox = 
      document.querySelector(".box");
      firstBox.style.backgroundColor =
      "lightblue"; // Change the background color to light blue
      firstBox.style.color = "white"; // Change the text color to white
  </script>
</body>

</html>

Output

Get/display elements by class name, each element reformatted.

3. Using document.querySelectorAll()

In this approach we are using the document.querySelectorAll() method. This method finds all elements that match a specific CSS selector, like class name. It gives you a static list, which means it wont automatically update if page changes.

Syntax:

var elements = document.querySelectorAll(".className");

Example: In below example we are using the querySelectorAll and we will print all the content which have that class name.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width,
    initial-scale=1.0">
  <title>Query Selector All Example</title>
  <style>
    .output {
      margin-top: 20px;
      padding: 10px;
      border: 1px solid #ccc;
      background-color: #f9f9f9;
    }
  </style>
</head>
<body>
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
  <div class="output" id="output3"></div>
  <script>
    var allBoxes = 
      document.querySelectorAll(".box");
    var output = 
      document.getElementById("output3");
    var content = "Contents of all boxes: <br>";
    allBoxes.forEach(function (box) {
      content += box.innerText + "<br>";
    });
    output.innerHTML = content;
  </script>
</body>
</html>

Output:

Get/display elements by class name, display contents of each element.

07. How to Get Value by Class Name using JavaScript?

This article will show you how to use JavaScript to get value by class name. To get the value of an element by its class name in JavaScript, you can use the getElementsByClassName() method. This method returns an array-like object of all elements with the specified class name. You can then access the value property of the first element in the array to get the value.

Example: In this example, we will get the classname of an element.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content=
    "width=device-width, initial-scale=1.0">
  <title>Get Value by Class Name</title>
</head>
<body style="text-align: center;">
  <h1 class="heading">
    GeeksforGeeks
  </h1>
  <p class="para">
    A computer science portal for geeks
  </p>
  <button onclick="myGeeks()">
    Get Value
  </button>
  <p id="result"></p>
  <script>
    function myGeeks() {
      // Get elements with the class name 'heading'
      let headingElements = 
        document.getElementsByClassName('heading');
        // Check if any elements with the 
        // specified class name exist
      if (headingElements.length > 0) {
        // Access the value of the first 
        // element in the collection
        let headingVal = headingElements[0].innerHTML;
        // Update the content of the 'result' element
         document.getElementById('result')
           .innerHTML = headingVal;
      } else {
        console.log(
          'Element with class name "heading" not found.');
      }
    }
  </script>
</body>

</html>

Output:

Get/display classname value.

Example 2: In this example, we will get the second element by class name.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">

    <title>Get Value by Class Name</title>
</head>
<body style="text-align: center;">
  <h1 class="heading text">
    GeeksforGeeks
  </h1>
  <p class="para text">
    A computer science portal for geeks
  </p>
  <button onclick="myGeeks()">
    Get Value
  </button>
  <p id="result"></p>
  <script>
    function myGeeks() {
      // Get elements with the class name 'heading'
      let headingElements = 
        document.getElementsByClassName('text');
      // Check if any elements with the 
      // specified class name exist
      if (headingElements.length > 0) {
        // Access the value of the first 
        // element in the collection
        let headingVal = headingElements[1].innerHTML;
          // Update the content of the 'result' element
          document.getElementById('result')
          .innerHTML = headingVal;
      } else {
        console.log(
          'Element with class name "text" not found.');
      }
    }
  </script>
</body>
</html>

Output:

.

08. How to Get Domain Name From URL in JavaScript?

In JavaScript, the URL object allows you to easily parse URLs and access their components. This is useful when you need to extract specific parts of a URL, such as the domain name. The hostname property of the URL object provides the domain name of the URL.

Prerequisite

Below are the following approaches to get a domain name from a URL in Javascript:

Table of Content

Using the URL Object

The new URL(url) constructor parses the URL and creates a URL object. This object has various properties that represent different parts of the URL. The hostname property of the URL object returns the domain name. For instance, for the URL https://www.example.com/path/to/resource?query=param, urlObject.hostname would return www.example.com. If the URL is invalid, the URL constructor will throw an error. In the catch block, you can handle this error, for example by logging it or returning a default value.

Example: This example shows the extraction of the domain name from a URL.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>How to get domain name from URL in JavaScript</h1>
    <p>Domain Name : <span id="span"></span></p>
    <script src="Index.js"> </script>
</body>
</html>

Output:

.

Using Regular Expressions

If you want more control or need to support environments where the URL object is not available, you can use regular expressions to extract the domain from the URL string.

Example: This example demonstrates the extraction of the domain name using Regex.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>How to get domain name from URL in JavaScript</h1>
    <p>Domain Name : <span id="span"></span></p>
    <script src="Index.js"> </script>
</body>
</html>

Output:

.

09. How to get protocol, domain and port from URL using JavaScript?

The protocol, domain, and port of the current page can be found by two methods:

Method 1: Using location.protocol, location.hostname, location.port methods: The location interface has various methods that can be used to return the required properties.

Syntax:

protocol = location.protocol;
domain = location.hostname;
port = location.port;

Example:

<!DOCTYPE html> 
<html> 
  
<head> 
  <title> 
    Get protocol, domain, and port from URL 
  </title> 
</head> 
  
<body> 
  <h1 style="color: green"> 
    GeeksforGeeks 
  </h1> 
      
  <b> 
    Get protocol, domain, and port from URL 
  </b> 
      
  <p> 
    Protocol is:  
    <span class="protocol"></span> 
  </p> 
      
  <p> 
    Domain is:  
    <span class="domain"></span> 
  </p> 
      
  <p> 
    Port is:  
    <span class="port"></span> 
  </p> 
      
  <button onclick="getDetails()"> 
    Get protocol, domain, port 
  </button> 
      
  <script type="text/javascript"> 
    function getDetails() { 
      protocol = location.protocol; 
      domain = location.hostname; 
      port = location.port; 
  
      document.querySelector('.protocol').textContent 
        = protocol; 
      document.querySelector('.domain').textContent 
        = domain; 
      document.querySelector('.port').textContent 
        = port; 
    } 
  </script> 
</body> 
  
</html>          

Output:

.

.

Method 2: Using the URL interface: The URL interface is used to represent object URL. It can be used for getting the port, domain, and protocol as it has inbuilt methods to get these values.

Note: This API is not supported in Internet Explorer 11.

Syntax:

current_url = window.location.href;
url_object = new URL(current_url);

protocol = url_object.protocol;
domain = url_object.hostname;
port = url_object.port;

Example:

<!DOCTYPE html>
<html>
      
<head>
  <title>
    Get protocol, domain, and port from URL
  </title>
</head>

<body>
  <h1 style="color: green">
    GeeksforGeeks
  </h1>
      
    <b> 
        Get protocol, domain, and port from URL 
    </b> 
      
    <p>Protocol is: <span class="protocol"></span></p> 
    <p>Domain is: <span class="domain"></span></p> 
    <p>Port is: <span class="port"></span></p> 
      
    <button onclick="getDetails()"> 
        Get protocol, domain, port 
    </button> 
      
    <script type="text/javascript">
        function getDetails() {
            current_url = window.location.href;
            url_object = new URL(current_url);
  
            protocol = url_object.protocol;
            domain = url_object.hostname;
            port = url_object.port;
  
            document.querySelector('.protocol').textContent
                    = protocol;
            document.querySelector('.domain').textContent
                    = domain;
            document.querySelector('.port').textContent
                    = port;
        }
    </script>
</body>
  
</html>                     

Output:

Get protocol, domain, and port from url.

Get protocol, domain, and port from url.

10. How to Extract the Host Name from URL using JavaScript?

Extracting the hostname from a URL using JavaScript means retrieving the domain part from a complete web address. This can be done using JavaScript’s URL object or methods like window.location, which allow easy access to the hostname of a URL.

What is URL?

A URL (Uniform Resource Locator) is the web address used to access resources on the internet, such as webpages, images, or files, through browsers.

Using the hostname property of the current window location

Here we are using JavaScript’s window.location object to extract the full URL and hostname. The window.location.href outputs the current page URL, while window.location.hostname retrieves only the domain part (hostname) of that URL.

Syntax

window.location.propertyname

Example : In this example, we will use the self URL, where the code will run to extract the hostname.

<!DOCTYPE html>
<html>

<head>
  <title>
    Get domain from URL
  </title>
</head>

<body>
  <h1 style="color: green">
    GeeksforGeeks
  </h1>

  <b>URL is:</b>

  <script>
    document.write(window.location.href);
  </script>

  <br>
  <b>hostname is:</b>

  <script>
    document.write(window.location.hostname);
  </script>
</body>

</html>

Output:

GeeksforGeeks URL is: https://ide.geeksforgeeks.org/tryit.php, 
      hostname is: ide.geeksforgeeks.org.

Extracting Hostname using indexOf and Looping

Here we extracts the hostname from a user-provided URL by locating the position of “://” using indexOf(). It then loops through characters starting after “://” until it encounters a “/”, constructing and displaying the extracted hostname on the page.

Syntax

url3.indexOf("://");

Example: In this example, we will ask for the URL to the user and then will perform the extraction of the hostname on that URL.

<!DOCTYPE html>
<html>
<head>
  <title>Extracting URL

Output:

Get/display url parameters.

11. How to Get the Current URL using JavaScript?

Here are two different methods to get the current URL in JavaScript.

01. Using Document.URL Property

The DOM URL property in HTML is used to return a string that contains the complete URL of the current document. The string also includes the HTTP protocol such as ( http://).

Syntax

document.URL

Return Value: It returns a string value that represents the full URL of the document.

<script>
// Get the current URL using document.URL
let currentUrl = document.URL;

// Log the URL to the console
console.log(currentUrl);
</script>

Output

http://127.0.0.1:5500/index.html

02. Using window.location.href Property

The window.location.href property of the HTML DOM Window object returns a string containing the URL of the current page. This property is part of the Location object, which contains information about the current location of the document.

Syntax

window.location.href
<script>
// Get the current URL using document.URL
let currentUrl = document.URL;

// Log the URL to the console
console.log(currentUrl);
</script>

Output:

http://127.0.0.1:5500/index.html

Note: Use the HTML file to copy paste and run the given code and you can see the output in the console, it will print the URL.

12. How to get URL Parameters using JavaScript?

To get URL parameters using JavaScript means extracting the query string values from a URL. URL parameters, found after the ? in a URL, pass data like search terms or user information. JavaScript can parse these parameters, allowing you to programmatically access or manipulate their values.

For getting the URL parameters, there are 2 ways:

Table of Content

Method 1: Using the URLSearchParams Object

The URLSearchParams interface provides methods to work with URL parameters. After splitting the URL with ?, the parameters part is passed to URLSearchParams(). Using entries(), you retrieve key/value pairs, allowing access to all URL parameters for further use.

Syntax:

let paramString = urlString.split('?')[1];
let queryString = new URLSearchParams(paramString);
for (let pair of queryString.entries()) {
   console.log("Key is: " + pair[0]);
   console.log("Value is: " + pair[1]);
}

Example: In this example we retrieves URL parameters using JavaScript. It splits the URL, extracts parameters with URLSearchParams(), and logs each key-value pair to the console when the button is clicked.

<!DOCTYPE html>
<html>
<head>
  <title>
    How To Get URL Parameters using JavaScript?
  </title>
</head>
<body>
  <h1 style="color:green;">
    GeeksforGeeks
  </h1> 
  <b>
    How To Get URL Parameters
    With JavaScript?
  </b>
  <p> The url used is: 
    https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks 
  </p>
  <p> 
    Click on the button to get the url 
    parameters in the console. 
  </p>
  <button onclick="getParameters()"> Get URL parameters </button>
  <script>
    function getParameters() {
      let urlString = 
        "https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks";
      let paramString = urlString.split('?')[1];
      let queryString = new URLSearchParams(paramString);
      for(let pair of queryString.entries()) {
        console.log("Key is:" + pair[0]);
        console.log("Value is:" + pair[1]);
      }
    }
  </script>
</body>
</html>

Output:

Get url parameters' key and value.

02. Method 2: Separating and accessing each parameter pair

The URL’s query string is split at ? to isolate parameters. Using split(“&”) divides parameters into an array. Looping through this array, each key-value pair is split by =, giving keys at the first index and values at the second, enabling parameter extraction.

Syntax:

let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
for (let i = 0; i < params_arr.length; i++) {
  let pair = params_arr[i].split('=');
  console.log("Key is:", pair[0]);
  console.log("Value is:", pair[1]);
}

Example: In this example we retrieves URL parameters by splitting the URL string manually. It extracts each key-value pair, splits them, and logs the results in the console when the button is clicked.

<!DOCTYPE html>
<html>
<head>
  <title> 
    How To Get URL Parameters using JavaScript? 
  </title>
</head>
<body>
  <h1 style="color:green;">
    GeeksforGeeks
  </h1> <b>
    How To Get URL Parameters
    With JavaScript?
  </b>
  <p> The url used is: 
    https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks 
  </p>
  <p> 
    Click on the button to get the url
    parameters in the console. 
  </p>
  <button onclick="getParameters()"> Get URL parameters </button>
  <script>
    function getParameters() {
      let urlString = 
        "https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks";
      let paramString = urlString.split('?')[1];
      let params_arr = paramString.split('&');
      for(let i = 0; i < params_arr.length; i++) {
        let pair = params_arr[i].split('=');
        console.log("Key is:" + pair[0]);
        console.log("Value is:" + pair[1]);
      }
    }
  </script>
</body>
</html>

Output:

Get URL parameters' key/value pairs.

13. How to parse URL using JavaScript?

Given an URL and the task is to parse that URL and retrieve all the related data using JavaScript. Example:

URL: https://www.geeksforgeeks.org/courses
When we parse the above URL then we can find
hostname: geeksforgeeks.com
path: /courses

Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use it for parsing the given URL.

// Store the URL into variable 
var url = "https://geeksforgeeks.org/pathname/?search=query"; 
      
// Created a parser using createElement() method 
var parser = document.createElement("a"); 
parser.href = url; 
      
// Host of the URL 
console.log(parser.host); 
      
// Hostname of the URL 
console.log(parser.hostname ); 
      
// Pathname of URL 
console.log(parser.pathname); 
      
// Search in the URL 
console.log(parser.search );

Output:

geeksforgeeks.org
geeksforgeeks.org
/pathname/
?search=query

Method 2: In this method we will use URL() to create a new URL object and then use it for parsing the provided URL.

// Store the URL into variable 
var url = 
  "https://geeksforgeeks.org:3000/pathname/?search=query"; 

// Created a URL object using URL() method 
var parser = new URL(url); 

// Protocol used in URL 
console.log(parser.protocol); 

// Host of the URL 
console.log(parser.host); 

// Port in the URL 
console.log(parser.port); 

// Hostname of the URL 
console.log(parser.hostname); 

// Search in the URL 
console.log(parser.search); 

// Search parameter in the URL 
console.log(parser.searchParams);

Output:

https:
geeksforgeeks.org:3000
3000
geeksforgeeks.org
?search=query
search=query

14. Manipulating HTML Elements with JavaScript

JavaScript is a powerful language that can be used to manipulate the HTML elements on a web page. By using JavaScript, we can access the HTML elements and modify their attributes, styles, and content. This allows us to create dynamic and interactive web pages.

Methods to Identify the elements to manipulate: There are several methods to identify the HTML elements that we want to manipulate using JavaScript. The most common methods are:

Accessing the properties of the elements: Once we have identified the HTML element that we want to manipulate, we can access its properties using JavaScript. For example, to access the text content of an element, we can use the innerHTML property. Similarly, we can access the style properties of an element using the style property.

Use Event Listeners to Respond to User Interactions: We can use event listeners to respond to user interactions such as clicking a button or hovering over an element. Event listeners are functions that are executed when a particular event occurs. For example, we can use the onclick event listener to execute a function when a button is clicked.

When building a website or web application, it's common to need to access and manipulate HTML elements using JavaScript. There are several methods available in JavaScript that allow you to do this, including getElementById(), getElementsByClassName(), and getElementsByTagName(). In this article, we'll take a systematic approach to use these methods and show you how to access and manipulate elements in your HTML documents.

Step 1: Identify the Element You Want to Manipulate:

The first step in working with HTML elements in JavaScript is to identify the element you want to manipulate. There are several ways to do this, depending on the specific element you're trying to access. Here are some common methods:

Syntax:

let element = document.getElementById("my-id");
let elements = document.getElementsByClassName("myClass");
let elements = document.getElementsByTagName("p");

Step 2: Access the Element's Properties and Methods:

Once you've identified the element you want to manipulate, you can access its properties and methods. Properties are values that describe the state of an element, such as its innerHTML, value, or src attributes. Methods are functions that allow you to manipulate an element in some way, such as changing its innerHTML, className, or style properties. Here are some examples of how to access an element's properties and methods:

// Accessing an element's methods
element.innerHTML = "New content!"; // changes the content of the element
element.classList.add("newClass"); // adds a new CSS class to the element
element.style.backgroundColor = "red"; // changes the background color of the element

Step 3: Use Event Listeners to Respond to User Interactions:

In addition to manipulating elements directly, you can also use JavaScript to respond to user interactions, such as clicks, mouse movements, or keyboard inputs. To do this, you can use event listeners, which are functions that are triggered when a specific event occurs on an element. Here's an example of how to add an event listener to a button element:

<button id="myButton">Click me!</button>
<script>
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
     console.log("Button clicked!");
});
</script>

In this example, we use getElementById() to access a button element with the ID "myButton". We then add an event listener to the button using the addEventListener() method. The event we're listening for is a "click" event, which is triggered when the user clicks the button. When the event is triggered, the function we passed as the second argument is executed, which logs a message to the console.

Example 1. Id selector

<!DOCTYPE html>
<html lang="en">
<head>
  <title>document.getElementById()</title>
</head>
<body>
  <h1 id="my-id">Hello World!</h1>
  <script>
    // Get element with id "my-id"
    var elements = document.getElementById("my-id");
    // Change the content of the element
    elements.innerHTML = "New content!";
  </script>
</body>
</html>

Output:

Get/update content using id getelementbyid & innerhtml.

Example 2. Class Selector:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>document.getElementsByClassName()</title>
</head>
<body>
  <p class="myClass">This is a paragraph.</p>
  <p class="myClass">This is another paragraph.</p>
  <script>
    // Get all elements with class "myClass"
    var elements = document.getElementsByClassName("myClass");
    // Change the content of the first element
    elements[0].innerHTML = "New content!";
  </script>
</body>
</html>

Output

Get/change content of first element.

Example 3: Here is an example of how to manipulate an HTML element using JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>DOM Manipulation</title>
</head>
<body>
  <h1 id="my-heading">Hello, World!</h1>
  <button id="my-button">Click me!</button>
  <script>
    const heading = document.getElementById("my-heading");
    const button = document.getElementById("my-button");
    button.addEventListener("click", function () {
      heading.innerHTML = "Button clicked";
      heading.style.color = "red";
    });
  </script>
</body>
</html>

Explanation: In this example, we first access the button element using the getElementById() method. We then add an event listener to the button using the addEventListener() method. The event we are listening for is the "click" event, and the function we want to execute when the event occurs is defined inline.

Output:

Click me, 'Hello, World' to 'Button clicked'.

Conclusion: In conclusion, manipulating HTML elements with JavaScript is a powerful technique that can be used to create dynamic and interactive web pages. By using the methods discussed above, we can identify and access the HTML elements on a web page and modify their properties to create the desired behavior.

15. How to use innerHTML in JavaScript?

The innerHTML property in JavaScript allows you to get or set the HTML content of an element as a string.

Syntax For

Getting HTML content of an element:

let element = document.getElementById("myElementId");
let htmlContent = element.innerHTML;

Setting HTML content of an element:

let element = document.getElementById("myElementId");
element.innerHTML = "New HTML content";

Here are step-by-step instructions on how to use the innerHTML property in JavaScript

Step 1: Access an HTML element

Use JavaScript to select the HTML element you want to manipulate. You can do this using various methods like document.getElementById(), document.querySelector(), or document.querySelectorAll().

<div id="myElement">Initial content</div>
let element = document.getElementById("myElement");

Step 2: Get the HTML content

If you want to retrieve the current HTML content of the element, use the innerHTML property.

let htmlContent = element.innerHTML;
console.log(htmlContent); 
// Output: Initial content

Step 3: Set the HTML content

If you want to replace or update the HTML content of the element, assign a new HTML string to the innerHTML property.

element.innerHTML = "<b>New content</b>";

Step 4: Verify the changes(optional)

You can optionally verify that the HTML content has been updated as expected by accessing the element again or using browser developer tools.

console.log(element.innerHTML);
 // Output: New content

Example: Here, we have show the code on how to use innerHTML in JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,
                                 initial-scale=1.0">
  <title>innerHTML Example</title>
  <style>
    .container {
      padding: 10px;
    }
  </style>
</head>
<body>
  <div class="container" id="myElement">Initial content</div>
  <button onclick="changeContent()">Change Content</button>
  <script>
    function changeContent() {
      let element = document.getElementById("myElement");
      element.innerHTML = "<b>New content</b>";
    }
  </script>
</body>
</html>

Output:

Change content live using innerHTML and button.

16. JavaScript innerHTML

The innerHTML property in JavScript is used to append the dynamic HTML or text content to an element using JavaScript. It is designed to add dynamic HTML, but developers also use it to add text content as well. It can be directly used with the element by selecting it using DOM manipulation.

Syntax:

selectedHTMLElement.innerHTML = "contentToAppend";

Example 1: The below code shows a basic implementation of innerHTML property to append HTML directly to an element.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, 
                                 initial-scale=1.0">
  <title>
    JavaScript innerHTML
  </title>
  <style>
    #container{
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="container">
    <h1 style="color: green;">
      GeeksforGeeks
    </h1>
    <h2>
      The below content is added dynamically
      using the innerHTML property in JavaScript.
    </h2>
  </div>
  <script>
    const container = document.getElementById('container');
    container.innerHTML += 
      `
      <h3>
        Hey Geek, <br/>
        Welcome to GeeksforGeeks
      </h3>
      <p>
        This content is added using the 
        innerHTML property.
      </p>
      `;
  </script>
</body>
</html>

Output:

Add content dynamically using innerHTML property.

Example 2: The below code implements the innerHTML property with click event to add HTML onclick to the button.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, 
                                 initial-scale=1.0">
  <title>
    JavaScript innerHTML
  </title>
  <style>
    #container {
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="container">
    <h1 style="color: green;">
      GeeksforGeeks
    </h1>
    <h2>
      Click the below button to dynamically add
      the HTML using the innerHTML property.
    </h2>
    <button id="myBtn">Add HTML</button>
  </div>
  <script>
    const myBtn = document.getElementById('myBtn');
    function clickHandler() {
      const container = 
        document.getElementById('container');
      container.innerHTML +=
        `
        <h3>
          Hey Geek, <br/>
          Welcome to GeeksforGeeks
        </h3>
        <p>
          This content is added using 
          the innerHTML property.
        </p>
        `;
    }
    myBtn.addEventListener('click', clickHandler);
  </script>
</body>
</html>

Output:

Click the below button to dynamically add the HTML using innerHTML property.