Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery object `toString()` method

I extended the jQuery object to return it's inner HTML...

$.fn.toString = function() {
  return this.html();
};

console.log("The inner HTML is: " + $("<div>Here, <i>there</i>, everywhere</div>"));

Is there any reason why this is not the default behaviour? Does this break something?


Updated to respond to answers/comments

Firstly, I don't see how it would break much, except for type checks which rely on coercing jQuery objects into string, and matching text in that string. Am I wrong about this?

This returns the outerHTML of all elements in a set, concatenated. Does this make any sense to anyone else? To me it makes quite a bit of sense.

var li, list;

$.fn.toString = function() {
  var out;
  out = [];
  $.each(this, function(k, v) {
    return out.push($(v)[0].outerHTML);
  });
  return out.join("\n");
};

list = $("<ul>\n  <li>some <a href='/'>link</a> items</li>\n  <li>some <a href='/'>link</a> items</li>\n  <li>some <a href='/'>link</a> items</li>\n  <li>some <a href='/'>link</a> items</li>\n  <li>some <a href='/'>link</a> items</li>\n</ul>");

li = $("li", list);

console.log("The html of it..: " + li);
like image 256
Billy Moon Avatar asked Mar 27 '13 15:03

Billy Moon


People also ask

When toString () method is invoked on an object what is returned?

The toString() method returns a string representing the object.

What is the function of toString () method?

The toString() method returns a string representing the source code of the specified Function .

How do I use string toString?

String toString() Method in java with Examples Since toString() method simply returns the current string without any changes, there is no need to call the string explicitly, it is usually called implicitly. Parameter: The method does not accept any parameters . Return Value: This method returns the string itself.


2 Answers

Object.toString returns a string representing the object (from the doc).

When talking about a jQuery object, the expected returned value for Object.toString is "[object Object]".

Making it return HTML would simply be bad design, and could break stuff up.

Plus, it makes sense to have different explicit methods depending on what we want to retrieve from a jQuery object: .html() for HTML, .text() for stripping tags.

like image 84
aaaaaa Avatar answered Nov 15 '22 17:11

aaaaaa


Well, jQuery object is home for lot more than just .html.If jQuery had to implement the toString, it should be generic enough to return based on the selector in jQuery object.

For example, If the selector picked multiple elements The version you have would simply return the first elements html content.

So what I am trying to say is that the toString is not simple as you think and I couldn't think of any great usage for toString as well.

like image 36
Selvakumar Arumugam Avatar answered Nov 15 '22 17:11

Selvakumar Arumugam