- How to append text to a div element?
- How to append text to div using ID in javascript?
- 4 Answers 4
- Add text before or after an HTML element
- 6 Answers 6
- How to Append or Add text to a DIV element using JavaScript
- Method 1 : Add text to DIV using innerHTML Property
- Method 2 : Add text to DIV using appendChild() Method
How to append text to a div element?
Danger, Will Robinson! This adds HTML, not text. If your Extra Stuff is provided by the user, you’ve just introduced a security vulnerabilty. Better to use @Chandu’s answer below.
Yes, it’s an XSS vulnerability. You’re far better off creating a text node with the content instead, as describe in the answer below.
This also woudn’t work in case div contains elements with event listeners or inputs with user-entered text. I recommend the answer by Chandu.
Yes, I definitely do not recommend this as this will destroy state of any checkboxes, event listeners.
var theDiv = document.getElementById(""); var content = document.createTextNode(""); theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by @BiAiB. So use caution if you are planning to use this version.
var theDiv = document.getElementById(""); theDiv.innerHTML += "";
I use this method with my «contenteditable» element with angularjs binding, and everything work correctly!
Should be the accepted answer indeed. Not only a beautiful way, but innerHTML will rebuild the DOM, and that is just not a good solution. Use appendChild().
This is better, but createTextNode won’t work if you are loading HTML. If you wanted to add list items, for example, this wouldn’t work. That is pretty limiting.
@Jake If HTML needs to be inserted instead of plain text, then don’t use createTextNode . There are several other methods for DOM manipulation related to this, e.g. insertAdjacentHTML , insertAdjacentElement , etc. Can’t call it “limiting” if you’re using the wrong tools. The question, though, could be clearer as to what is meant by “data”.
Beware of innerHTML , you sort of lose something when you use it:
theDiv.innerHTML = theDiv.innerHTML + 'content';
Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.
If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):
var newNode = document.createElement('div'); newNode.innerHTML = data; theDiv.appendChild(newNode);
yes but this will cause there to be an extra div inside the parent div which is not needed and might mess up some css styles
@Neal no it’s not. It’s neither correct or incorrect. It just depends on what the OP needs to append: text, html code or something else.
@Neal this is a perfectly good way of appending the data, and is more versatile than document.createTextNode() .
If you want to do it fast and don’t want to lose references and listeners use: .insertAdjacentHTML();
«It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation.»
Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml
// one var d1 = document.getElementById('one'); d1.insertAdjacentHTML('afterend', 'two'); // At this point, the new structure is: // onetwo
How to append text to div using ID in javascript?
Here i am using function to print the values to div with id=»mylist» .i am using the loop and calling the printList() function with the value and i am printing the value in printList() but its not working.how can i do this?
function coucity() < for (var i = 0; i < 10; i++) < printList(i); >> function printList(city)
Also, on your line document.getElementById(«myDIV»).append(writecity); you should have the same name of the div id (in your example it’s «mylist» but on your code it’s «myDIV». Makes sure they match
4 Answers 4
var writecity = document.createTextNode(city); document.getElementById("mylist").appendChild(writecity);
Basically, you only append other DOM Node (as child) to DOM Nodes. so you use document.createTextNode() to create node and document.appendChild() to add it as a child to existing node.
Problem is document.write returns nothing, also using it is not recommended. Secondly dom does not have function append , instead it is appendChild .
Try document.createTextNode and appendChild :
function coucity() < for (var i = 0; i < 10; i++) < printList(i); >> function printList(i)
You may also try innerHTML :
function coucity() < for (var i = 0; i < 10; i++) < printList(i); >> function printList(i)
An example of appending a text node to a div , referenced by id, with a delay.
function appendDelayedTextNode(element, text, delayMs) < setTimeout(function () < element.appendChild(document.createTextNode(text)); >, delayMs); > var mylist = document.getElementById('mylist'); appendDelayedTextNode(mylist, 'one', 1000); appendDelayedTextNode(mylist, 'two', 2000); appendDelayedTextNode(mylist, 'three', 3000);
There are a couple of things wrong with your code, all of which can easily be found out by checking the JavaScript console.
- You don’t call coucity anywhere (but a comment shows that is is called from elsewhere, so that shouldn’t be the problem)
- document.write should be document.createTextNode
- getElementById(«myDIV») does not find the div with id mylist
- append should be appendChild
- and finally, if you correct all these errors, it only outputs the digits 0 through 9 instead of cities.
I can’t help you with the last one, but with the other errors corrected, here is the result.
function coucity() < for (var i = 0; i < 10; i++) < printList(i); >> function printList(city) < var writecity = document.createTextNode(city); document.getElementById("mylist").appendChild(writecity); >coucity();
To add a delay, there are several methods available. Which would be best depends on your needs. In this simple case, you can even write
Add text before or after an HTML element
If i have an HTML element like
my text must be added here
6 Answers 6
Yes, you can create a text node with document.createTextNode(‘the text’)
Then you can insert it like an element, with appendChild or insertBefore.
Example that insert a text before #childDiv:
var text = document.createTextNode('the text'); var child = document.getElementById('childDiv'); child.parentNode.insertBefore(text, child);
You could also try the «insertAdjacentText» or «insertAdjacentHTML» methods: developer.mozilla.org/en-US/docs/Web/API/…
div.insertAdjacentHTML( 'beforeBegin', yourText );
where div is your child-DIV.
You can also add it after. div.insertAdjacentHTML( ‘afterEnd’, ‘my text added after’ ); Does anyone know if you can remove it? (without using a class or id)
@tkerwood Sure. You need to retrieve a reference to that Text node and then use the .removeChild() method (on its parent).
If you just need text, I find that element.insertAdjacentText(position, text) is flexible for many scenarios and is also compatible with older browsers like IE6. Where position is exactly where you want the text to be and text is the text node or just a string. The options are:
- ‘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.
let div = document.getElementById('parentDiv'); div.insertAdjacentText('afterbegin', 'My Plain Text..');
In regards to the topic and the users question for inserting before or after, here is an example for after:
var text = document.createTextNode("my text must be added here."); var childTag = document.getElementById("childDiv"); childTag.parentNode.insertBefore(text, childTag.nextSibling);
If the childTag does not have any siblings, it is okay because the insertBefore method handles this case and simply adds it as the last child.
Also can possibly use the appendChild() method after creating text node then add your childTag via the parentNode.
How to Append or Add text to a DIV element using JavaScript
I have explained jQuery .append() and .appendTo() methods in my previous articles, which also serves the same purpose. However, if you want to stick to pure JavaScript to append or add text, contents etc. to a <div> element, then this post is for you.
There are two different methods in JavaScript, using which you can easily add text or contents to a <div> element, dynamically.
Method 1 : Add text to DIV using innerHTML Property
The innerHTML property will add new contents to a <div> element that is either empty or already has some content in it. For example,
<body> <p> <input type='button' onclick='fillData()' value='Fill Div with Data'> </p> <div > <p> Content inside p element. </p> </div> </body> <script> let fillData = () => < let ele = document.getElementById('container'); ele.innerHTML += 'Hello, I am Arun'; > </script> </html>
Using the innerHTML property, you to add text, markup and styles to the element, dynamically. It means, you can append tags like <b> or <span> etc. to the content.
For example, ele.innerHTML += ‘<b>Hello, I am Arun</b>’; . The Hello. string has <b></b> tags within the quotes, to bold the string.
There’s another important thing, which is worth noting is the use of += , immediately after «.innerHTML». This will allow you to add (in-fact append) new contents with existing contents or, elements that already exists inside the <div> element. See the above example, I already have a <p> element with some contents in it.
Method 2 : Add text to DIV using appendChild() Method
You can also use the appendChild() method in JavaScript to add text or contents to a <div>. Its different from innerHTML property that I have explained in the first example (see above).
With innerHTML, you can directly provide texts, markups, style etc. to the element.
With «appendChild()», you have to create node (a text node here) for the parameter, to append the contents to the <div>.
<body> <p> <input type='button' onclick='fillData()' value='Click to fill DIV with data'> </p> <div > <p> Content inside p element. </p> </div> </body> <script> let fillData = () => < let ele = document.getElementById('container'); let node = document.createTextNode ('Hello, I am Arun'); ele.appendChild(node); > </script> </html>
This too will serve the purpose. It will add text to a <div> element. However, using this method you can only add plain texts. You cannot add additional markups or style to the text.
Both the methods, that I have described above have its pros and cons. Use it judiciously, as both fits in different situations. Remember, if you are using innerHTML property to add extra or new content to an existing content, use “+=” after the property. Or else, it will remove all content along with elements (nodes etc.) and add completely new content the element.
ele.innerHTML = 'Hello, I am Arun'; // will add completely new content and remove previous content
ele.innerHTML += 'Hello, I am Arun'; // will add new content with existing content
Hope, you find this post useful. Thanks for reading ☺ .