Change the Text of a Div Using Javascript

  1. Change div Text Using the innerHTML Attribute
  2. Change the Contents of a Div With textContent Node Attribute
  3. Inner HTML Versus textcontent Security Aspect
  4. 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";

In the above code snippet, we get the content of a HTML div element using the htmlElement.innerHTML. Here, the htmlElement is the actual HTML object. Similarly, we can set the content to a div using the same attribute, the innerHTML of the element. We just assign the text content to the innerHTML.

  • Usage:
<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);
}

Output:

Hello World!!
Hello bunny!!

Before we apply the .innerHTML, we need to select the HTML element. We can do it in various ways. Javascript has many functions that we can use to query for elements from the DOM. Following are a few of the most commonly used methods.

  • 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!!"
}

Output:

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.

<div id="div-element"></div>
window.onload = function() {
    var el = document.getElementById("div-element");
    el.innerHTML = `<div style="height: 20px; background: lightgreen" onclick="alert('Danger!!!')">`;
}

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 <div style="height: 20px; background: lightgreen" onclick="alert('Danger!!!')"> 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.

<div id="div-element"></div>
window.onload = function() {
    var el = document.getElementById("div-element");
    el.textContent = `<div style="height: 20px; background: lightgreen" onclick="alert('Danger!!!')">`;
}

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 <img> where the browser replace the content with the loaded image. The following code details the usage.

<div class="pvw-title"><span>Facts</span></div>
.pvw-title span {
  display: none;
}
.pvw-title:after {
  content: 'whatever it is you want to add';
}
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Text

  • Copy Text to Clipboard in JavaScript
  • Get Text Area Value in JavaScript
  • JavaScript Change Text