Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  23] [ 6]  / answers: 1 / hits: 39315  / 11 Years ago, wed, march 27, 2013, 12:00:00

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);

More From » jquery

 Answers
61

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.


[#79300] Wednesday, March 27, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dahlias

Total Points: 730
Total Questions: 104
Total Answers: 101

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;