sg552
sg552

Reputation: 1543

Multiple random id in element

I have many span element with many ids such as these:

<span id="spn1" class="span-text">hello</span>
<span id="spn2" class="span-text">world</span>
<span id="spn3" class="span-text">12345</span>

It could be 1 or 100 span element. If 100 span was created so the id will be spn100. No problem with that. Now I have problem with javascript code because I hardcoded the ids when the span such as these:

var text = $("#spn1").text() + "\r\n" + $("#spn2").text() + "\r\n" + $("#spn3").text();

The javascript code above was hardcoded so if 100 span was created; my copy function will not worked. How do I solve this problem?

Full code : http://jsfiddle.net/p3h7j4eb/

Thanks in advance

Upvotes: 2

Views: 59

Answers (2)

Poul Bak
Poul Bak

Reputation: 10929

You can iterate over all elements with you classname, using the 'each' function like this:

var text = '';
$('.span-text').each(function ()
{
    text += $(this).text() + '\r\n';
}

Upvotes: 3

trincot
trincot

Reputation: 350079

You can use the CSS class as selector and just iterate over that with $.map. Then there's no more need for all those id properties:

var text = $.map($(".span-text"), function(span) {
    return $(span).text();
}).join("\r\n");

console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="span-text">hello</span>
<span class="span-text">world</span>
<span class="span-text">12345</span>

Upvotes: 4

Related Questions