0

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>

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks. It works. Seems like the problem appears in logic part when I used "not" before. $("a:not([href$='.zip'])").addClass('notzip'); covers the result of $("a[href$='.zip']").addClass('zip'); when adding class 'notzip' to href that doesn't suffix with .zip or .html. Why it happens?
@JiayanYang I don't understand your question. Can you show how you used :not in your case, to see what might've been wrong?
@JetoThe :not works well. However when I $("a:not([href$='.zip||.html)'])").addClass("download"); , the results cover the $("a[href$='.zip']").addClass('zip');. In your example the green also becomes red.
$("a:not([href$='.zip||.html)'])") is not correct. What are you trying to achieve? You want to match anything that doesn't end with either .zip or .html?
@JetoExactly. Want to find anything except href ends with .zip or .html. This is why I said 'Seems like the problem appears in logic part when I used "not()" before.' Sorry for my poor English:)
|
0

If I understood correctly, this should work!

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

1 Comment

@testingKikiHi thanks for your advice. I think href='.zip' should be href $= '.zip' since I need to add class for href end with .zip. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.