0

I want to have the following in my javascript code using jquery:

$('.attrs span:nth-child(1)').text() + ' | ' + $('.attrs span:nth- 
child(2)').text() + ' | ' + $('.attrs span:nth-child(3)').text() ...

Though the number of children span elements will change so I have worked on it dynamically like so:

      function getString(containerElem) {
            var str = '';
            for (var i = 0; i < containerElem.children().length; i++) {
                    ((i + 1) == containerElem.children().length) ? str += '$(\'.attrs span:nth-child('  + (i + 1) +  ')\').text()' : str += '$(\'.attrs span:nth-child('  + (i + 1) +  ')\').text() + \'  \' + ';
            }
            return str;
       }

When I return it as a string the jQuery will not work as the $ is a string now as well, can I do this using some flag or global variable to add to the string somehow ie $.getString() + $.getString2()... depending on how many span elements my container has?

1
  • 1
    If something like this $('.attrs span:nth-child(1)').text() is returned as a string, You could use eval(Yourstring), but if I was you, i would look for a better way of doing this. Commented Aug 21, 2018 at 10:04

2 Answers 2

4

You don't need to know how many <span> you have, you can just select them all with
$('.attrs span').

Then, just get their text values with innerText and use Array#join to create your String:

let spans = $('.attrs span');

let result = spans.get().map(e => e.innerText).join(' | ');
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="attrs">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

The jQuery children method can be called with a selector as argument, to limit the list of children to that selector. This way you can find all child elements that are a SPAN, iterate over that list of elements read the inner text.

function getString(containerElem) {
  var str = '';

  containerElem.children('span').each(function(i, element) {
    str += jQuery(element).text();
  });

  return str;
}

console.log(getString(jQuery('.attrs')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="attrs">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.