N
N
Nikita2021-06-23 15:41:51
JavaScript
Nikita, 2021-06-23 15:41:51

How to iterate through all elements with the same class, select their texts and add them to one variable separated by commas?

Hello! How to iterate through all elements with the same class in jQuery, select their texts and add them to one variable separated by commas?
For example, there is a structure like this:

<td class="model">456</td>
<td class="model">443</td>
<td class="model">12</td>

I need to iterate over all these elements with the model class and add texts separated by commas to one variable: Next, I want to save it in cookies: I try to do it like this, but it doesn’t work:
var models = "456,443,12";
document.cookie = "models ="+models+"; path=/";
$('body').on('click','#button-confirm',function(){
var models = '';
$("td.model").each(function(){
models = $(this).html() + ',';
console.log(models);
document.cookie = "models="+models+"; path=/"; // библиотека для сохранения в куки
});
});

How to do it differently?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-23
@MrNix21

const models = Array
  .from(document.querySelectorAll('.model'), n => n.innerText)
  .join(', ');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question