The Wayback Machine - https://web.archive.org/web/20241004195603/https://www.geeksforgeeks.org/how-to-create-editable-div-using-javascript/
Open In App

How to create editable div using JavaScript ?

Last Updated : 31 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will be explaining to you how to create an editable div using HTML, CSS, and JavaScript. An editable div is one on which is you will click then it will generate an editable text area to edit or to write any text on your browser itself. After editing, when you click on somewhere else on your browser then that text will be displayed as a constant text (without editable).

Prerequisites: You should be familiar with the basics of HTML, CSS, and JavaScript.

Creating structure: Create two files for HTML, and JavaScript. To create these files run the following command

Syntax: 

$ touch index.html app.js

Step 1: Edit index.html. This file contains the following Code. HTML

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

        <h1 style="color: green;  
                   text-align: center;">
            Creating Editable Div GeeksforGeeks
        </h1>

        <div style="text-align: center; 
                    margin-left: 35%;" 
             class="container">
            <div id="first"></div>
        </div>

    </body>
  
    <script src="app.js"></script>
</html>

Step 2: Edit the app.js file. This file contains the  following Code. JavaScript

// Creating a new element

let editableDiv = document.createElement('div');
        
// Adding text to that created element

let value = localStorage.getItem('text');   
let text;

if (value == null){
    text = document.createTextNode
    ('Click on it to edit this Editable Div');
}
else{
    text = document.createTextNode(value);
}

editableDiv.appendChild(text);
editableDiv.setAttribute('id', 'elem');
editableDiv.setAttribute('class', 'elem');
editableDiv.setAttribute('style',
'font-size:3rem;border:3px solid;
 width:350px;height:200px;');

// Access the main container

let container = document.querySelector('.container');

// Inserting the element with id = first

container.insertBefore(editableDiv, first);

// Adding event listener to the divElem

editableDiv.addEventListener('click',function (){

let lengthOfTextAreas = 
    document.getElementsByClassName('textarea').length;
                    
if(lengthOfTextAreas == 0){
    let html = elem.innerHTML;
    editableDiv.innerHTML =

    `<textarea class="textarea form-control" 
    id="textarea" rows="3"> 
    ${html}</textarea>`;
}

// Listening the blur event on textarea

let textarea = document.getElementById('textarea');

textarea.addEventListener('blur',function() {
    elem.innerHTML = textarea.value;
    localStorage.setItem(
    'text', textarea.value); 

    })
});   

Final Solution: This is the combination of the above two steps.

HTML

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

        <h1 style="color: green;  
                   text-align: center;">
            Creating Editable Div GeeksforGeeks
        </h1>

        <div style="text-align: center; 
                    margin-left: 35%;" 
             class="container">
            <div id="first"></div>
        </div>

    </body>
    
    <script>

        // Creating a new element

            let editableDiv = document.createElement('div');
            
            // Adding text to that created element
            
            let value = localStorage.getItem('text');   
            let text;
            
            if (value == null){
                text = document.createTextNode
                ('Click on it to edit this Editable Div');
            }
            else{
                text = document.createTextNode(value);
            }
            
            editableDiv.appendChild(text);
            editableDiv.setAttribute('id', 'elem');
            editableDiv.setAttribute('class', 'elem');
            editableDiv.setAttribute('style',
            'font-size:3rem;border:3px solid;
             width:350px;height:200px;');
            
            // Access the main container
            
            let container = document.querySelector('.container');
            
            // Inserting the element with id = first
            
            container.insertBefore(editableDiv, first);
            
            // Adding event listener to the divElem
            
            editableDiv.addEventListener('click',function (){
            
            let lengthOfTextAreas = 
                document.getElementsByClassName('textarea').length;
                                
            if(lengthOfTextAreas == 0){
                let html = elem.innerHTML;
                editableDiv.innerHTML =
            
               `<textarea class="textarea form-control" 
                id="textarea" rows="3"> 
                ${html}</textarea>`;
            }
            
            // Listening the blur event on textarea
            
            let textarea = document.getElementById('textarea');
            
            textarea.addEventListener('blur',function() {
                elem.innerHTML = textarea.value;
                localStorage.setItem(
               'text', textarea.value); 
            
                })
            }); 
              
    </script>

</html>

Output: When you will open it on any browser then the following output would be generated.

file


Similar Reads

How to copy the content of a div into another div using jQuery ?
Given an HTML document containing some div element and the task is to copy a div content into another div as its child using jQuery. There are two approaches to solve this problem that are discussed below: Approach 1: First, select the div element which needs to be copied into another div element.Select the target element where the div element is c
2 min read
How to Make a Child Div Element Wider than Parent Div using CSS ?
When the child div element has a fixed width that is wider than the parent div element, it will display overflow outside of the parent element. Because the overflow is hidden by default, one approach is to utilize the overflow attribute to enable it on an element. Another approach includes setting the position property of the parent div element to
2 min read
How to overlay one div over another div using CSS
Creating an overlay effect simply means putting two div together at the same place but both the div appear when needed i.e while hovering or while clicking on one of the div to make the second one appear. Overlays are very clean and give the webpage a tidy look. It looks sophisticated and is simple to design. Overlays can create using two simple CS
2 min read
How to force child div to be 100% of parent div's height without specifying parent's height?
When designing a website, you may want to create a layout where a child div element fills up the height of its parent div element. However, you may not know the exact height of the parent div element and you don't want to specify it. In this article, we will explore different approaches to force a child div element to be 100% of its parent div elem
3 min read
How to center a div on the edge of another div in SASS ?
In this article, we will see how to centre a div on the edge of another div using SASS. SASS is an extension of CSS that stands for Syntactically Awesome Style Sheets. It helps us to create things like variables, nested rules, etc. So that we can reuse the code. Centering a div on the edge of another div is not a difficult task. We can achieve it b
4 min read
How to make Parent Div Activate Styling of Child Div for Hover and Active ?
In this article, we will see how to make parent div activate styling of child div for hover and active. We can do this by using Pseudo-classes like hover and active. Approaches to make parent div activate styling of child div for hover and activeUsing Pure CSS: with pseudo-classesUsing CSS and JavaScript: without pseudo-classesMethod 1: Using Pure
2 min read
How to make div fixed after scroll to that div ?
In this article, we will see how to make a div fixed after you scroll to it by using the position property with a sticky value. This effect is generally used on websites when an important message needs to be shown. Set the property position to sticky to create elements that behave as fixed positions whenever the user scrolls to that position. Fixin
4 min read
How to clear all div's content inside a parent div ?
In this article, we are given an HTML document containing div elements and the task is to remove the existing HTML elements using jQuery. To accomplish this task, we can use the following methods: Table of Content jQuery remove() methodjQuery empty() methodjQuery html() methodjQuery remove() methodThe remove() method in jQuery is used to remove the
2 min read
How to Overlay/Hover Div in Flexbox Container Div?
In CSS, overlay/hover effects can be achieved by using Flexbox containers to center content and applying styles to reveal overlays on hover. By positioning elements absolutely within a Flexbox container, overlays can cover the entire content area. These are the following approaches: Table of Content Using ::before Pseudo-elementUsing an Overlay Div
3 min read
How to Center a Div within another Div?
We are given a HTML div inside another div tag and the task is to center the inside div. The div tag is used to construct a division or section of an HTML document in which other elements of HTML is placed. Syntax:<div> <h3>'This is a div of the web page.>/h3> <p>This is some text in a div element.</p></div> Exam
4 min read
How to create a simple editable canvas textbox using Fabric.js?
In this article, we are going to create a canvas textbox using Fabric.js. The canvas means text written in the Textbox is movable and can be stretched according to requirement. Further, the text itself can be edited into anything else too because it is a textbox. Creating structure: To make this possible we are going to use a JavaScript library cal
2 min read
How to create an Editable Table with add delete and search filter using ReactJS ?
Tables are used to display a set of data. In some projects, you need to implement the dynamic table with editable/non-editable modes where a user can add or delete any row. Also, Material UI for React has a customizable Table Component available, and it is very easy to integrate, but there is no such functionality to handle rows addition and deleti
6 min read
How to set cursor position in content-editable element using JavaScript ?
In order to set caret cursor position in content editable elements like div tag is carried over by JavaScript Range interface. The range is created using document.createRange() method. Approach 1: First, create Range and set position using above syntax. Get user input from input tag using jQuery $("input']").val(); On button click assign input valu
4 min read
How to create a moving div using JavaScript ?
In this article, we will learn to create a moving HTML div using JavaScript. The div will move left to right using HTML, CSS, and JavaScript. Approach: We have to create an HTML div and add some CSS to the div using a glass ball. In CSS, we add some background-color to the body and give some height, width, and color to the div.Now we will add margi
2 min read
How to design editable listview using jQuery Mobile plugin?
In this article, we will learn how to design an editable listview feature using the jQuery mobile plugin. The plugin provides an intuitive user interface to add or delete list items to the existing list. To design and implement the plugin, please download the required pre-compiled files or libraries from the link and save it in your working folder.
3 min read
How to remove border from an editable element using CSS ?
Given an HTML document containing some document and the task is to remove border from an editable element using CSS. It is a default behavior of any element which have content-editable attributes set to true whenever, the element gets a focus it will get a border around them. The task can be done by using the [attribute] selector to select all elem
1 min read
How to make a text input non-editable using jQuery ?
An HTML document containing the input text area and the task is to make the text input non-editable with the help of jQuery. There are two approaches that are discussed below: Approach 1:We are going to set the property readonly to true. To set the readonly property, we will use a prop() method. Example: [GFGTABS] HTML <!DOCTYPE HTML> <htm
2 min read
How to Make Text Input Non-Editable using CSS?
There are situations where you might want to create non-editable input fields. HTML and CSS both provide ways to achieve this. 1. The read-only Attribute in HTMLThe read-only attribute in HTML is used to make a text input field non-editable, meaning users can see the content but cannot modify it. This is helpful when you want to display information
2 min read
How to create a div using jQuery with style tag ?
Creating an <div> element with a style tag using jQuery can be done in the following steps. Steps: Create a new <div> element.Create an object with all the styles that we want to apply.Choose a parent element, where to put this newly created element.Put the created div element into the parent element. Example 1: This example will create
2 min read
How to create a pop-up div on mouse over and stay when click using jQuery ?
In this article, we will learn how to create a pop-up div on mouseover and stay when click using jQuery. Approach: First, we create an HTML div element that we want to pop up when we mouse over on an element and set its display property to none in CSS style.display:none;In the script tag, we create a variable flag and set its value to -1. $flag = -
2 min read
How to create navigation bar using <div> tag in HTML ?
In this article, we will know to create the navigation bar using the <div> tag in HTML. The Navbar is a navigation header that contains the links to navigate to the different pages or sections of the site that helps to make the website interactive. The navbar is an important & fundamental component for any site format, as it represents th
3 min read
Create a Div Element using jQuery
In this article, we will see how to create a <div> element using jQuery. We can create a div element with the following steps: Steps to Create a Div ElementCreate a new <div> element.Choose a parent element, where to put this newly created element.Put the created div element into the parent element.Example 1: This example creates a <
2 min read
How to create three boxes in the same div using HTML and CSS ?
We can place three or more different divs side by side in the same div using CSS. You can achieve this using Flexbox, but you need to use wrapper divs and apply different flex directions to each of them to make the grid layout work. You can set the height and width of the div by using CSS properties. Syntax:flex: flex-grow flex-shrink flex-basis |
3 min read
How to add a tooltip to a div using JavaScript?
Adding tooltip to div element displays a pop-up, whenever the mouse hovers over div. Syntax: < div title = "" > </div> <script> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> Tooltip Methods: .tooltip("show"): It is used to show the tooltip. .tooltip("hide"): It is us
2 min read
How to append data to <div> element using JavaScript ?
To append the data to <div> element we have to use DOM(Document Object Model) manipulation techniques. The approach is to create a empty <div> with an id inside the HTML skeleton. Then that id will be used to fetch that <div> and then we will manipulate the inner text of that div. Syntax: document.getElementById("div_name").innerT
1 min read
How to get the div height using JavaScript ?
In this article, we will see How to get the div height using Javascript. We can do this by following ways: Using the offsetHeight property.Using the clientHeight property.Using getBoundingClientRect() Method. Method 1: Using the offsetHeight property: The offsetHeight property of an element is a read-only property and is used to return the height o
3 min read
How to Combine multiple elements and append the result into a div using JavaScript ?
Combining multiple elements and appending elements to DOM is a crucial process, it would become a time-consuming process. If not handled properly so as a developer we should know how to update the DOM effectively. So following are the three ways to append HTML elements to DOM. The following methods are in decreasing order of time complexity. Use jQ
3 min read
How to Change Background Color of a Div on Mouse Move Over using JavaScript ?
The background color of the div box can be easily changed using HTML, CSS, and Javascript. We will use the querySelector() and addEventListener() methods to select the element and then apply some math logic to change its background color. The below sections will guide you on how to create the effect. HTML Code: In this section, we will create a bas
2 min read
How to rotate an HTML div element 90 degrees using JavaScript ?
An element can be rotated 90 degrees by using the transform property. This property is used to move, rotate, scale, and others to perform various kinds of transformation to elements.  ApproachThe rotate() transformation function can be used as the value to rotate the element. It takes one parameter that defines the rotation angle. The rotation angl
2 min read
How to find the width of a div using vanilla JavaScript?
To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels. Below are the different approaches to finding the width of a div using vanilla JavaScript: Table of Content Using offsetWidthUsing clientW
3 min read