Can not pass text string to jquery function?

What happened to my jquery script?

Here is the script

function debug(message){
  $("body").append("<div id=\"debug\">"+ $(message) +"</div>"):
}
debug("show this debug message in the div");

Here is the resulting html I get

<div id="debug">[object Object]</div>

the html i expect is

<div id="debug">show this debug message in the div</div>
+3
source share
2 answers

You insert the object into, $ (message) instead of the variable message. Try the following:

    function debug(message){
      $("body").append("<div id=\"debug\">"+ message +"</div>"):
    }
+4
source

You convert a string to a jquery object with $(message). basically you are messageno longer making a string, but a jquery selector. Try the following:

function debug(message){
  $('body').append($('<div>').attr('id','debug').text(message));
}

note. I use .attr and .text, as this extra bid is more secure when adding information.

. : ID - HTML. , , perm. "div", .text(), debug [CSS] div.

+8

Source: https://habr.com/ru/post/1784461/


All Articles