Prabin Poudel Prabin Poudel - 29 days ago 9
Javascript Question

Add "target= '_blank' " to an anchor tag excluding a given id

How to add a

target=_blank
attribute to an anchor tag, except a button and certain div. How do I not add target attribute to "call-control" class and ID with #?

I've tried this:



$('a:not(.call-control,"#")').attr('target', '_blank').addClass('checkMate');

/* then later... */
$('.checkMate').attr("target", "");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="call-control">
<span id="incomingCallBrand"></span>
</div>
<div>
<a href="#" class="comms-icon" id="iambusy"></a>
<span>Peter</span>
</div>




Answer Source

Regardless of what specific links you're trying to select, your selector is invalid.

To apply the selection to any links that don't have a certain class, you're looking for $("a:not('.class')"):

To apply the selection to any links that don't have a certain class, you're looking for $("a:not('[href=#'])"):

These can be combined as $("a:not('.class-control, [href=#]')"):

$("a:not('.call-control, [href=#]')").attr("target", "_blank").addClass('checkMate');
.checkMate {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="call-control" href="#" rel="noopener noreferrer">Same Page (doesn't get the target)</a>
<br />
<a class="call-control" href="http://www.google.com" rel="noopener noreferrer">Google (doesn't get the target)</a>
<br />
<a href="http://www.facebook.com" rel="noopener noreferrer">Facebook (gets the target)</a>

Also, it's important to note that target=_blank has a significant security vulnerability, which can be exploited with window.opener(). This can be seen here. To fix this, you also need to add rel="noopener noreferrer" to your links (as above).

Hope this helps! :)