简体   繁体   中英

select link having href with a specific get variable

in the example below - how to select the link having c=ni

 let a = 'c=ni'; let target = '...'; // select `alink` having `a` inside its href //target.addClass('act');
 .act{background:orange;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class='alink' href='index.php?c=kb'>lorem</a> <br> <a class='alink' href='index.php?c=ni'>lorem</a>

Plain JS

You could use querySelector with * wildcard

 let a = 'c=ni'; let target = document.querySelector(`a[href*='${a}']`) target.classList.add('act');
 .act{background:orange;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class='alink' href='index.php?c=kb'>lorem</a> <br> <a class='alink' href='index.php?c=ni'>lorem</a>

jQuery

The query selector is the same, use first() to select one only

 let a = 'c=ni'; $(`a[href*='${a}']`).first().addClass('act')
 .act{background:orange;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class='alink' href='index.php?c=kb'>lorem</a> <br> <a class='alink' href='index.php?c=ni'>lorem</a>

You can use attribute selectors. They can be used for javascript, jQuery or CSS. Read more about Attribute selectors here

 let target = $('.alink[href*="c=ni"]'); target.addClass('act');
 .act{background:orange;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class='alink' href='index.php?c=kb'>lorem</a> <br> <a class='alink' href='index.php?c=ni'>lorem</a>

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