Search code examples
jqueryattributestagsinverse

jquery how select element by inverse name attribute


I want to select items by reverse attribute name only:

I select with a[^safe] or a[!safe], wrong

My HTML:

<ul>
  <a href="#">Link Base</a>
  <a href="#">Link Base</a>
  <a href="#">Link Base</a>
  <a href="#">Link Base</a>
  <a safe href="#">Link Base</a>
  <a safe href="#">Link Base</a>
</ul>

My jQuery Code:

$("a[^safe]").each(function(){
    $(this).css({"color": "red", "border": "2px solid gold"});
});

My jsFiddle:

https://jsfiddle.net/Lpr4tow1/1/


Solution

  • You can use the :not() selector to make the modification, or just make a css rule for it and do without the javascript all together.

    Though, if you choose the pure css way, you'll most likely want to scope the selector down so it is not so global.

    $('a:not([safe])').addClass('not-safe')
    .not-safe {
      color: red;
      border: 2px solid red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <a href="#">Link Base</a>
      <a href="#">Link Base</a>
      <a href="#">Link Base</a>
      <a href="#">Link Base</a>
      <a safe href="#">Link Base</a>
      <a safe href="#">Link Base</a>
    </ul>

    a:not([safe]) {
      color: red;
      border: 2px solid red;
    }
    <ul>
      <a href="#">Link Base</a>
      <a href="#">Link Base</a>
      <a href="#">Link Base</a>
      <a href="#">Link Base</a>
      <a safe href="#">Link Base</a>
      <a safe href="#">Link Base</a>
    </ul>