简体   繁体   中英

selector in Javascript

I'm beginner in Javascript. I have a list of links and I want to select links end with .zip and add class zip from css;

add select links end with not .zip and add class notzip from css.

I use $("a[href $='.zip']").addClass("zip") to do the first task but cannot do the task 2 by add ! or not(). It is recommended by $this and location, filter function. How can I do that?

      <ul>
    <li><a href="a.html">a</a></li>
    <li><a href="b.pdf">b</a></li>
    <li><a href="c.zip">c</a></li>
  </ul>

You can make use of :not :

 $(function() { $("a[href$='.zip']").addClass('zip'); $("a:not([href$='.zip'])").addClass('notzip'); $("a:not([href$='.zip']):not([href$='.html'])").addClass('notzipnorhtml'); var exts = ['html', 'pdf', 'zip']; $('a' + exts.map(ext => ':not([href$=".' + ext + '"])').join('')) .addClass('notanyofthose'); }); 
 .zip { color: green; } .notzip { color: red; } .notzipnorhtml { color: purple; } .notanyofthose { color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="a.html">a</a></li> <li><a href="b.pdf">b</a></li> <li><a href="c.zip">c</a></li> <li><a href="d.exe">d</a></li> </ul> 

If I understood correctly, this should work!

$("a[href='.zip']").addClass("zip");
$("a[href!='.zip']").addClass("notzip");

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