简体   繁体   中英

JS - Add Class to link that contains a certain word

I'm trying to use Jquery to add a class to all links which contain a certain keyword "keyword". Any help would be much appreciated

 $(document).ready(function(){ $('.list').each(function(){ var $this = $(this); if($this.text().indexOf('Keyword') > -1) $this.closest('.list a').addClass('selected-link') }) })
 .selected-link { color:red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li><a href="#">Keyword</a></li> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> </ul>

You need find a inside li tag as $this.find('a') , $this.text() is content of li tag

 $(document).ready(function(){ $('.list').each(function(){ var $this = $(this); if($this.find('a').text().indexOf('Keyword') > -1) $this.find('a').addClass('selected-link') }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li><a href="#">Keyword</a></li> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> </ul>

Iterate over the .list a s instead - the <a> s which are descendants from the .list :

 $('.list a').each(function() { var $this = $(this); if ($this.text().indexOf('Keyword') > -1) { $this.addClass('selected-link'); } });
 .selected-link { color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li><a href="#">Keyword</a></li> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> </ul>

Note that there's no need for a big library like jQuery for something this trivial, this is easy to accomplish in vanilla JS:

 for (const a of document.querySelectorAll('.list a')) { if (a.textContent.includes('Keyword')) { a.classList.add('selected-link'); } }
 .selected-link { color: red; }
 <ul class="list"> <li><a href="#">Keyword</a></li> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> </ul>

I suppose you are looking for this?

 $(document).ready(function() { document.querySelectorAll('.list a').forEach(el=> { if (/Keyword/.test(el.textContent) ) { el.classList.add('selected-link') } }) })
 .selected-link { color:red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li><a href="#">Keyword</a></li> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM