2

I am looping through elements using jQuery like this:

$(".myelement").each(function() {
  $element = $(this).closest(".panel").attr("id");
  console.log($element);
});

This is working correctly and I am seeing each of the elements it finds in my console log. I am now trying to get a string containing each element that looks like this:

#element1, #element2, #element3

What is the easiest way to do this? Does anybody have an example they can point me at?

3 Answers 3

2

You could use map() to build an array of the id then join() it, something like this:

var ids = $(".myelement").map(function() {
  return '#' + $(this).closest(".panel").prop("id");
}).get().join(', ');

console.log(ids);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the suggestion, map looks more appropriate than each. The returned list is missing the # that my each function returns though, any way to add that back in to each element returned?
Ah yes, you can concatenate it to the string you return, eg return '#' + $(this).closest....
Thanks, works perfectly. Reading up on map now to make sure I have a full understanding of what is going on
2

You could use an array to store them by adding the # in every iteration, then after the loop end join them using join() method like :

var ids = [];

$(".myelement").each(function() {
  ids.push('#' + $(this).closest(".panel").attr("id"));
});

console.log(ids.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element1" class="panel">
  <span class="myelement">My element 1</span>
</div>
<div id="element2" class="panel">
  <span class="myelement">My element 2</span>
</div>
<div id="element3" class="panel">
  <span class="myelement">My element 3</span>
</div>

Comments

2

Try with map()

The .map() method is particularly useful for getting or setting the value of a collection of elements.

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

You can use map(), get() and join() in the following way:

var $element = $(".myelement").map(function(){
  return $(this).closest(".panel").attr("id"); 
}).get().join(', ');
console.log($element);

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.