Strange behavior in jQuery html method

Any good reason $ ("p") is. Does html (0) make all paragraphs empty and not contain the character '0'?

Instead of assuming that I found a bug in jQuery, this is probably a misunderstanding on my part.

+3
source share
5 answers

jQuery only takes a string as an argument to a valmethod parameter html(). If you pass in a number like you, it will cause an override of the method html(), which sets the contents of the element, but the value of the argument will eventually be null or an empty string.

Try the following:

$("p").html((0).toString())

Related Documentation

+5
source

, - if (newContent == false) - ? , ...

, , , "0" ( ), .

:

var myNum = 0;
$('p').html('' + myNum);
0

text() html().

0

, html, , , , , html , spoon16.

(function($) {
  var oldHtml = $.fn.html;
  $.fn.html = function (content) {
    oldHtml.apply(this, [content.toString()]);
  }
})(jQuery);

, , , .

, - .

0

I geuss you missed part of jQuery’s work,

$('p')

returns all paragraphs and the html (val) function:

Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).

http://docs.jquery.com/Attributes/html#val
Therefore, if you just want to set the content for the first p, use

$("P").eq(0).html( 'something' );

or get html:

$("P").eq(0).html();

http://docs.jquery.com/Core/eq#position
more about jQuery selectors:
http://docs.jquery.com/Selectors

-1
source

All Articles