I'm trying to add a .dl
class to all links that have any file suffixes (extensions) except .pdf
and .html
. I don't want my other (both external and internal) links to be affected.
$('a').not("a[href^='http://'], a[href^='https://'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#'], a[href$='.pdf'], a[href$='.html']").addClass( 'dl' );
With my code some relative and external links get affected. What can I do to fix it?
Thank you!
This is an approach you may can consider to try.
The filename array represents all suffixes which you want to add the class.
var fileNames = ["suffix1", "suffix2"];
$("a").each(function(index, element){
fileNames.forEach(function(fileName){
if($(element).attr("href").startsWith(fileName)){
$(element).addClass("dl");
}
});
});
.dl {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="suffix1">addClass suffix1</a>
<a href="http://">don't add</a>
<a href="suffix2">addClass suffix2</a>
<a href="https://">don't add</a>