Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting each line text in navbar and add as id

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>
like image 625
sam kh Avatar asked Apr 12 '20 17:04

sam kh


2 Answers

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>
like image 107
Sajeeb Ahamed Avatar answered Oct 24 '22 00:10

Sajeeb Ahamed


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>
like image 1
palaѕн Avatar answered Oct 23 '22 23:10

palaѕн