Reputation:
I've got a system generated table that houses links in each of it's row elements. Each of these links has a unique 4 digit value at the end of the link.
The goal is to iterate through each of these table elements, grab the link it holds and then slice that link down to just the final 4 characters.
I've got this running right now:
HTML
<td class="lc_Cell">
<p>
<a href="thelink">Link #1</a>
</p>
</td>
<td class="lc_Cell">
<p>
<a href="thelink">Link #2</a>
</p>
</td>
<td class="lc_Cell">
<p>
<a href="thelink">Link #3</a>
</p>
</td>
<td class="lc_Cell">
<p>
<a href="thelink">Link #4</a>
</p>
</td>
Jquery
var TRLink = $(".lc_Cell > p > a").attr("href"); //The original URL the program spits out
var TR_ID = TRLink.slice(-4); // Storing just the 4 digits I need
var NewLink = $(".lc_Cell > p > a").attr("href","mynewlinktosendsomeoneto"+ TR_ID);
// my new link that utilizes the 4 characters from the original
This kind of works... the initial variable stores the link of the first instance it finds (in my actual code there are 3 others). When I create the NewLink variable it then overwrites ALL occurrences.
In a perfect world I'd iterate through and store the original links, do my slice and then iterate through and re-build a new link for each.
I came across the "each.()" command in jQuery but didn't have much luck getting a solution to work on my own.
Any help is greatly appreciated!
Upvotes: 1
Views: 83
Reputation: 337560
To achieve this you could use map()
to build an array of the last four characters of the href
attributes of all the relevant a
elements:
var ids = $('.lc_Cell a').map(function() {
return this.href.slice(-4);
}).get();
console.log(ids);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="lc_Cell">
<p>
<a href="thelink1234">Link #1</a>
</p>
</td>
<td class="lc_Cell">
<p>
<a href="thelink2345">Link #2</a>
</p>
</td>
<td class="lc_Cell">
<p>
<a href="thelink3456">Link #3</a>
</p>
</td>
<td class="lc_Cell">
<p>
<a href="thelink4567">Link #4</a>
</p>
</td>
</tr>
</table>
That being said, given your aim to update the href
attributes on the a
elements it makes more sense in this case to provide a function to attr()
which you can use to return a new value based on their current one. Something like this:
$('.lc_Cell a').attr('href', function(i, href) {
var id = href.slice(-4);
return 'mynewlinktosendsomeoneto' + id;
});
Upvotes: 2