#5858 closed enhancement (worksforme)
allow user to add a delimiter to the text() function
Reported by: | aklimchak | Owned by: | |
---|---|---|---|
Priority: | major | Milestone: | 1.4.1 |
Component: | unfiled | Version: | 1.4 |
Keywords: | attribute text delimiter | Cc: | |
Blocked by: | Blocking: |
Description
If I want to get all of the text from a series of elements, I would think that this function should allow me to delimit them. This could be an optional parameter. As an example:
<span>1</span> <span>2</span> <span>3</span>
$("span").text(); would function as it always has
$("span").text("|"); would output "1|2|3"
$("span").text(" * "); would output "1 * 2 * 3"
Change History (4)
comment:1 Changed 13 years ago by
comment:2 Changed 13 years ago by
For your workaround, rather than mutating each element, use 'map' to get a jQuery object of each of the texts, then 'join' to make a delimited string:
var x = $("span").map(function() {
return $(this).text();
}).toArray().join(",");
I think that the delimiter is just one of a series of set-based things you might want to do on the texts of a set of elements. Rather than adding a delimiter, it'd be better to have something that gets you an array or jq object... then you can do whatever you want with it.
I'd probably go for something like this:
var mytexts = $(myselector).texts()
mytexts would then be a jquery object containing the text of each element. This could be implemented thus:
$.fn.texts = function() {
return $(e).map(function() {
return $(this).text();
});
}
Then, for your scenario, do this:
var x = e.texts().toArray().join(",");
I think the default behavior of text() concatenating the text of each element is a little bit weird - it comes from a jquery object representing a set of elements, but text() kinda only applies to a single element... so, yeah, the behavior when there's multiple elements is always going to be a bit weird. I think if you have an operation on a set, you should really return a set.
So, yeah, it's a bit weird... but I'm not sure that adding a delimiter parameter is the way to do. Given that there's a very simple workaround, there's probably no need to change jquery.
Options:
- Leave as is.
- Implement the delimit functionality, as described by the ticket.
- Add texts(), which returns a jquery object of the text of each element, as I've described.
comment:3 Changed 13 years ago by
Resolution: | → worksforme |
---|---|
Status: | new → closed |
This is a great forum discussion topic. It seems there are plenty of existing solutions so I'll close this bug report.
I'm new to jQuery and I just figured out how to get my intended result.
$("span").append("|").text();
However, that alters the page. So maybe this is still legit, maybe not.