Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append/prepend/create a text node with jQuery

Possible Duplicate:
Escaping text with jQuery append?

My HTML is somewhat like this:

<div id="selector">Hello World</div> 

Now I'd like to append some text to this div. I know that I could simply use

$('#selector').append(text); 

but this wouldn't escape any special characters in text. Another way is to wrap the text in a span:

$('#selector').append( $('<span>').text(text) ); 

But this is ugly, because it creates unnecessary markup. So my current solution is to manually create a TextNode:

$('#selector').append( document.createTextNode(text) ); 

I was wondering whether there is any jQuery-style way to do this?

like image 814
Niko Avatar asked Oct 01 '11 10:10

Niko


People also ask

What is append and prepend in jQuery?

append() & . prepend() .append() puts data inside an element at the last index; while. . prepend() puts the prepending element at the first index.

How do you use prepend and append?

The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.

What does prepend do in jQuery?

prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).

How do you append something in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.


2 Answers

The createTextNode approach is probably the best way to go. If you want to have a jQuery-ish syntax, you could make a plugin.

$.fn.appendText = function(text) {     return this.each(function() {         var textNode = document.createTextNode(text);         $(this).append(textNode);     }); }; 
like image 186
lonesomeday Avatar answered Oct 04 '22 17:10

lonesomeday


$.text() accepts also a function as parameter. This function will receive an index and the current text. The return value of the function will be set as the new text.

.text( function )

function
Type: Function( Integer index, String text ) => String
A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

$("li").text(function(idx, txt) {     return txt + " <item>";  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <ul>      <li>1</li>      <li>2</li>      <li>3</li>  </ul>
like image 25
Andreas Avatar answered Oct 04 '22 18:10

Andreas