35

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,212
  • 11
  • 43
  • 55

4 Answers4

60

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
  • 165,323
  • 34
  • 234
  • 359
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,372
  • 1
  • 26
  • 24
8

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,405
  • 1
  • 17
  • 15
5

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
  • 137,034
  • 36
  • 218
  • 257