Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy all the links to a one variable

Tags:

jquery

foreach

I have to do such thing:

I have html list:

<ul>
   <li><a href="abc"></a></li>
   <li><a href="bac"></a></li>
   <li><a href="cab"></a></li>
</ul>

I would like to include in one variable all the links and separated them by a comma - resulting in variable string "abc, bac, cab."

I can display these link:

var link = $ ('ul li a') .attr ('href');
alert (link);

But I can't do a loop such as: for each 'li', copy the link, and then display: 'link1, link2, link3'

like image 747
Lech Avatar asked Dec 14 '22 05:12

Lech


1 Answers

Use map() method in jQuery, which helps to generate an array based on the element. Later join the values using Array#join method.

var link = $('ul li a')
  .map(function() { // iterate over and generate array
    return $(this).attr('href') // retrive href attribute value
  })
  .get() // retrieve the result as array from jQuery object
  .join(', '); // join the value for prefered output 

alert(link);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <a href="abc"></a>
  </li>
  <li>
    <a href="bac"></a>
  </li>
  <li>
    <a href="cab"></a>
  </li>
</ul>
like image 110
Pranav C Balan Avatar answered Dec 21 '22 09:12

Pranav C Balan