Identify if a link points to an image, and add a class

1

On one page, there are links pointing to images.

<a class="native-class" href="http://localhost/test/wp-content/uploads/2017/10/7-3.jpg"></a>

I'm aware that I could add another class using the native-class class but what I want to do is add another class to that specific link if the href is an image. .png, jpg, gif etc.

    
asked by anonymous 01.04.2018 / 00:03

2 answers

1

You can do this by going through all the links:

var links = document.querySelectorAll("a");

for(var x=0; x<links.length; x++){
   
   if(links[x]
   .href // pego o valor do href
   .split(".") // quebro o valor
   .pop() // pego a extensão
   .match(/jpg|gif|png/)) // comparo
   links[x].classList.add("nova-class"); // adiciono a classe
   
}
<a class="native-class" href="http://localhost/test/wp-content/uploads/2017/10/7-3.jpg">Link 1</a>
<a class="native-class" href="http://localhost/test/wp-content/uploads/2017/10/7-3.tiff">Link 2</a>
  

Separate the names of the desired extensions from the regex of match by a slash   vertical | .

    
01.04.2018 / 00:16
0

A "pitaco" here, I think more succinctly:

document.querySelectorAll('a').forEach(link => {
    if ( /\.(jpg|png|gif)/g.test(link.href) ) {
        link.classList.add('nova-classe')
    }
    // mostrar
    console.log(link.classList.toString())
})
<a class="native-class" href="http://localhost/test/wp-content/uploads/2017/10/7-3.jpg">jpg</a>
<a class="native-class" href="http://localhost/test/wp-content/uploads/2017/10/7-3.png">png</a>
<a class="native-class" href="http://localhost/test/wp-content/uploads/2017/10/7-3.gif">gif</a>
<a class="native-class" href="http://localhost/test/wp-content/uploads/2017/10/7-3.webp">webp</a>
<a class="native-class" href="http://localhost/test/wp-content/uploads/2017/10/7-3.svg">svg</a>
    
01.04.2018 / 00:41