So, I have following list:
<li><a class="name" title="<?php echo $names;?></a></li>
And let say, you get the following names: Steve, Mike, Sean, Ryan.
Now, I have the following js:
var names= [];
function GET_NAMES ()
{
//Something
}
So, when the GET_NAMES() function is loaded, I want to collect all the values in the title in the list and put in the var names=[]
How do I collect the values into variable?
var names=[]
$('li a').each(function() {
names.push($(this).attr('title'))
})
console.log(names)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<a class="name" title="Steve"></a>
</li>
<li>
<a class="name" title="Steve1"></a>
</li>
<li>
<a class="name" title="Steve2"></a>
</li>
<li>
<a class="name" title="Steve3"></a>
</li>
</ul>
Try this way
Using jQuery, you will first need to select the <a> elements, and then you can get the title attributes for each.
$("li a").each(function(){
names.push($(this).attr('title')); // this will get the title and push it onto the array.
}
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