Jiayan Yang
Jiayan Yang

Reputation: 101

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>

Upvotes: 0

Views: 403

Answers (2)

Jeto
Jeto

Reputation: 14927

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>

Upvotes: 3

Kiki
Kiki

Reputation: 117

If I understood correctly, this should work!

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

Upvotes: 0

Related Questions