36

What can I use in jquery instead of document.createTextNode(' ') js line.

I'm trying to do sth like this :

js : divButtons.appendChild(document.createTextNode(' '));

jquery : $("#divButtons").append(?????);

penguru
  • 4,342
  • 11
  • 46
  • 56

4 Answers4

59

Please be careful with the existing answers. They show how to append HTML. HTML is not Text. Treating text as HTML is a) a bug and b) dangerous.

Here is a sane solution:

$('selector').append(document.createTextNode('text < and > not & html!'))

This is using jQuery only for the append part. Nothing wrong with using createTextNode. jQuery uses createTextNode internally in its text(str) function.

usr
  • 168,620
  • 35
  • 240
  • 369
10
var jqTextNode = $(document.createTextNode(' '));

creates the jquery representation of a text node. i don't think there is a shortcut which works reliable.

Christian
  • 3,551
  • 1
  • 28
  • 24
7

I know this is an old question, but I was looking for the same thing...

The closest method that I'm aware of is the .text() method.

This escapes text securely in the same way as creating a new TextNode, but it can only be used to specify the full contents of a node.

e.g.

var mynode = jQuery('#node-id');
mynode.text('A<B implies B>A');
Tim Wintle
  • 2,423
  • 1
  • 17
  • 15
4

There is no equivalent in jQuery for createTextNode. You can always use the DOM method, or write a jQuery wrapper around it. The closest thing you may be able to find is when creating new elements, you can specify the text part separately.

$('<div>', {
    text: '<hello world>'
});
Anurag
  • 140,337
  • 36
  • 221
  • 257