So I just decided to play with jquery, wrote this code:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="style.css"> <script src="jquery-2.2.3.js"></script> </head> <body> <div id="message_area"></div> <textarea id="for_send" title="Test"></textarea> <button id="send">Submit</button> <script src="script.js"></script> </body> </html> 

It was html, here is js:

 $(document).ready(function(){ $("#send").click(function(){ var text; text = $("#for_send").val(); $('#message_area').append('<div></div>').text(text).addClass('.message'); }); }); 

The task is as follows: I try to insert messages (text from a div) into a window with messages (#message_area). Everywhere, the append () method is described ... inserts the append ... element into the end of the content of the element for which I have something not like this: the content is not recorded, but replaced; is not inserted at the end, and the previous contents of #message_area are removed and a new one is inserted from #for_send. I've been sitting on this for a long time and I don’t understand what the problem is. The textarea dimensions are specified in the css file

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

Let's see what you do

 $('#message_area') // получаем элемент по id .append('<div></div>') // добавляем в конец элемента новый div .text(text) // меняем содержимое элемента* .addClass('.message'); // добавляем класс к элементу* 

* here you have a problem, you calculate that text added to the created div , but the append method returns the context in which it is called, and not the element that we passed as an insertion parameter

Output to console:

 var element = $("<div id='div'></div>"); element.append("<a>"); // что вернется? Давайте проверим element == element.append("<a>"); // true 

That is, you add a div , and then insert text into the #message_area element, but the text method already overwrites the entire content, hence the result that you describe

Solution : create an additional variable and work with it

 var messageDiv = $("<div class='message'></div>"); messageDiv.text(text); $('#message_area').append(messageDiv); 

UPD (suggested by @Grundy)
Option without ext. variable

 $("<div class='message'></div>") .text(text) .appendTo('#message_area'); 
  • one
    without additional variable, if you use appendTo - Grundy

This is how it will work.

In your example, you add an empty div and then assign the element with id #message_area class = message and insert the text from $ ("# for_send") into it. Val ()

 $(function(){ $("#send").on('click', function(){ var text = $("#for_send").val(); $('#message_area').append($('<div/>', {text: text, class: 'message'})); }); });