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'
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With