- JavaScript HTML DOM — Changing HTML
- Changing HTML Content
- Example
- Example
- Changing the Value of an Attribute
- Example
- Dynamic HTML content
- Example
- document.write()
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Set content javascript div
- # Change the Text of an Element in JavaScript
- Change the Text of a Div Using Javascript
- Change div Text Using the innerHTML Attribute
- Change the Contents of a Div With textContent Node Attribute
- Inner HTML Versus textcontent Security Aspect
- Change the div Text Using the :after Pseudo Element
- Related Article — JavaScript Text
JavaScript HTML DOM — Changing HTML
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
This example changes the content of a
element:
Example
- The HTML document above contains a
element with id=»p1″
- We use the HTML DOM to get the element with id=»p1″
- A JavaScript changes the content ( innerHTML ) of that element to «New text!»
This example changes the content of an element:
Example
- The HTML document above contains an element with id=»id01″
- We use the HTML DOM to get the element with id=»id01″
- A JavaScript changes the content ( innerHTML ) of that element to «New Heading»
Changing the Value of an Attribute
To change the value of an HTML attribute, use this syntax:
This example changes the value of the src attribute of an element:
Example
- The HTML document above contains an
element with id=»myImage»
- We use the HTML DOM to get the element with id=»myImage»
- A JavaScript changes the src attribute of that element from «smiley.gif» to «landscape.jpg»
Dynamic HTML content
JavaScript can create dynamic HTML content:
Example
document.write()
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
Never use document.write() after the document is loaded. It will overwrite the document.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Set content javascript div
Last updated: Jan 12, 2023
Reading time · 2 min
# Change the Text of an Element in JavaScript
Use the textContent property to change the text of an element.
The textContent property will set the text of the element to the provided string, replacing any of the existing content.
Here is the HTML for the examples.
Copied!DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="container">Initial Textdiv> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const div = document.getElementById('container'); // ✅ Change (replace) the text of the element div.textContent = 'Replacement text'; // ✅ Change (replace) the content with HTML div.innerHTML = `span style="background-color: lime">Replacement HTMLspan>`; // ✅ Append / Prepend text to the element div.insertAdjacentText('beforeend', ' appended text'); // ✅ Append / Prepend HTML to the element div.insertAdjacentHTML( 'beforeend', ` appended HTML
`, );
We used the textContent property on the div to change its text content.
The textContent property can also be used to read the text content of an element and its descendants.
Setting textContent on an element removes all of the element’s children and replaces them with a single text node with the provided string.
If you need to completely replace the HTML content of the div , use the innerHTML property.
Copied!const div = document.getElementById('container'); // ✅ Change (replace) the text with HTML div.innerHTML = `span style="background-color: lime">Replacement HTMLspan>`;
The innerHTML property gets or sets the HTML contained within the element.
By setting the property on the element, you effectively replace the previously contained HTML in the div .
You shouldn’t use user-generated data without escaping it when setting the HTML of an element because it would leave your application vulnerable to XSS attacks.
If you need to append/prepend text to the existing content of the div element, use the insertAdjacentText method instead.
Copied!const div = document.getElementById('container'); // ✅ Append / Prepend text to the element div.insertAdjacentText('beforeend', ' appended text');
The insertAdjacentText method takes the following 2 parameters:
- position — the position relative to the element where the text should be inserted. Can be one of the following 4:
- beforebegin — before the element itself.
- afterbegin — just inside the element, before its first child.
- beforeend — just inside the element, after its last child.
- afterend — after the element itself.
- data — the string from which to create a new text node to insert at the given position.
We inserted text just inside the div element, before its last child, but you can change the value of the position parameter depending on your use case.
If you need to insert HTML into the div , use the insertAdjacentHTML method.
Copied!const div = document.getElementById('container'); // ✅ Append / Prepend HTML to the element div.insertAdjacentHTML( 'beforeend', ` appended HTML
`, );
The first parameter the insertAdjacentHTML method takes is the same as insertAdjacentText — the position at which the HTML should be inserted.
The second parameter is an HTML string containing the content you want to insert.
Note that this method shouldn’t be used with user-provided data without it being escaped, as it would leave you open to cross-site scripting attacks.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Change the Text of a Div Using Javascript
- Change div Text Using the innerHTML Attribute
- Change the Contents of a Div With textContent Node Attribute
- Inner HTML Versus textcontent Security Aspect
- Change the div Text Using the :after Pseudo Element
The div elements are non-interactive by nature. Javascript infuses life into it by making it interactive. We may need to reword the text displayed by a div . For instance, while implementing an Edit functionality, we may reuse the screens designed for developing the Add feature. Just the wordings need to be changed. As for the Add functionality, we may need to reword the Add keyword of a button to Update and so forth. Let us look at a few ways in which we can change the text of a div dynamically.
Change div Text Using the innerHTML Attribute
Unlike other programming languages, we do not use getter and setter methods to set a text to HTML elements. The HTML element object for a div has an attribute called the innerHTML . We can use it to get and set the content of the HTML object. Here the HTML object will be live. That is, it reflects any change to the element property in the browser on refresh.
Following is the syntax for using the innerHTML.
var text = htmlElement.innerHTML; htmlElement.innerHTML = "New Text";
div id="div-element">Hey there!!div>
window.onload = function() document.getElementById("div-element").innerHTML = "Hello World!!"; console.log(document.getElementById("div-element").innerHTML); var el = document.getElementById("div-element"); el.textContent = "Hello bunny!!"; console.log(document.getElementById("div-element").innerHTML); >
- getElementById() : This function of the document interface is used to select an element from the DOM using its id , specified in the HTML. The function returns the HTML object corresponsing to the selected element.
- getElementsByClassName : We can query for element based on the css class name with the getElementsByClassName function. More than one elements are returned as an array of HTML objects by this javascript method.
- getElementsByName : There is another way to select the elements with the name attribute. We specify the name attribute for the node in HTML. This method returns an array of HTML objects. We can use it, especially if we are interested in selecting multiple elements with a specific style, CSS class and acting upon them all in one go.
- getElementsByTagName : We can also select element based on their HTML tags using the getElementsByTagName() function. For instance, we can perform some operations on all the div elements in a section of DOM etc. As the name suggests, the function returns an array of HTML objects.
- querySelector : Javascript querySelector function is a bit more generic and can be used to select HTML elements with the css query . The function returns the first element that satisfies the condition passed in its parameter.
- querySelectorAll : This one is similar to the querySelector , with the only difference that it will return more than one element that satisfies the css query format passed as a parameter to it.
Change the Contents of a Div With textContent Node Attribute
Even though we use the innerHTML quite often, there is a security risk involved in using it. It is related to how the innerHTML replaces the content of the HTML element. The innerHTML attribute removes all the sub HTML nodes in a single shot and adds the new content as assigned in it.
The security risk comes as the innerHTML attribute allows us to insert any piece of HTML code, even if it is a harmful code. We will discuss this aspect in the next section. MDN recommends using node.textContent for changing the text of an element. It replaces the child nodes inside the HTML with the text we assign in the textContent parameter. Refer to the following code to understand the usage.
div id="div-element">Hey there!!div>
window.onload = function() var el = document.getElementById("div-element"); el.textContent = "Hello bunny!!" >
Here, we select the HTML element, div , before changing the text. We use the getElementById() function to query the element from the DOM. We then use the textContent to change the text of the div . This change will not be distinguished when the screen loads. As soon as the browser loads the webpage, the window.onload function gets executed, and the text change will happen. So the end-user sees the newer text always. The change of the old text to new is not evident on screen load. We can also play around with the textContent inside the setTimeOut method to see the change.
Inner HTML Versus textcontent Security Aspect
The innerHTML attribute differs from the textContent . Both the attributes take text as input but, what is the security vulnerability here? In the innerHTML , it is possible to add malicious code. Refer to the following code snippet. Here, the change reflects, and the innerHTML code will get executed. As shown in the following code snippet, on clicking the light green HTML div element, an undesirable alert pops up on the screen.
window.onload = function() var el = document.getElementById("div-element"); el.innerHTML = ``; >
If we assign the same content in textContent for the div element, it will not render it as an HTML element. Javascript renders the content as text on the screen. So we can literally see the displayed as text in the webpage. This aspect makes code more secure and reliable. Hence, if we intend to change the text of an HTML element, the Javascript best practices (as supported by MDN) recommend using textContent instead of innerHTML attribute.
window.onload = function() var el = document.getElementById("div-element"); el.textContent = ``; >
Change the div Text Using the :after Pseudo Element
If the text change is trivial, we can use CSS to alter the div text. We use the :after pseudo HTML element, wherein we add the text that we wish to display in the content attribute. It does not apply to HTML elements like where the browser replace the content with the loaded image. The following code details the usage.
div class="pvw-title">span>Factsspan>div>
.pvw-title span display: none; > .pvw-title:after content: 'whatever it is you want to add'; >