34

If I want to set the text of a <div id="error"></div> to "Test message here", do I do:

 $('<div id="error">').text('Test message here');

I tried this and it's not working. Thoughts?

Pointy
  • 389,373
  • 58
  • 564
  • 602
sehummel
  • 5,276
  • 23
  • 86
  • 137

4 Answers4

68

You create a new div and set its text, but you don't insert it anywhere. What you need to do is:

var el = $('<div id="error">').text('Test message here');
$(document).append(el);

or, if the div is already there:

$("#error").text('Test message here');
Gabi Purcaru
  • 29,852
  • 9
  • 74
  • 91
27
 $('#error').text('Test message here');
Dejan Marjanović
  • 19,004
  • 7
  • 50
  • 66
1

Try:

$('<div id="error"></div>').text('Test message here');

You also need to insert the new element somewhere in the page.

Álvaro González
  • 135,557
  • 38
  • 250
  • 339
-4

It's preferable to use

$("#error").html('Test message here') 

instead of simply

.text('Text Msg');
gotqn
  • 37,902
  • 44
  • 152
  • 231
Murugan
  • 51
  • 6