i want to get each link's text and add it to link as ID.
here is my navbar code:
<div class="navbar">
<ul>
<li><a href="#">link1</a></li>
<li><a href="#">link2</a></li>
<li><a href="#">link3</a></li>
<li><a href="#">link4</a></li>
<li><a href="#">link5</a></li>
</ul>
</div>
You are wanting this I think-
const links = [...document.querySelectorAll('a')];
links.forEach(link => {
link.setAttribute('id', link.innerText);
});
<div class="navbar">
<ul>
<li><a href="#">link1</a></li>
<li><a href="#">link2</a></li>
<li><a href="#">link3</a></li>
<li><a href="#">link4</a></li>
<li><a href="#">link5</a></li>
</ul>
</div>
You can loop over the links using .each()
method like:
$('.navbar a').each(...)
Then get each link text using .text()
like:
$(this).text().trim()
// .trim() is used to remove whitespace from both sides of this string
and finally set the ids using .attr()
like:
$(this).attr('id', value);
Working Demo:
$('.navbar a').each(function(){
$(this).attr('id', $(this).text().trim());
});
[id^='link']{background-color: yellow;text-decoration: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar">
<ul>
<li><a href="#">link1</a></li>
<li><a href="#">link2</a></li>
<li><a href="#">link3</a></li>
<li><a href="#">link4</a></li>
<li><a href="#">link5</a></li>
</ul>
</div>
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