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

Asked

Viewed 45 times

1

On one page, there are links that point to images.

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

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

  • I did an answer but I was in doubt. What do you mean by "specific link"?

  • @dvd that’s the comment I was writing when you removed the answer rsrsr. Yes, it is a very elegant solution! But in fact, what I would like to use as a value only href if it is ['jpg','png','gif','svg'], it is because of that class native-classe will not always exist, I just put it to exemplify.

  • @dvd I want that if a link has in href the address for an image, add a class.

  • @dvd your answer was right and solved the problem if I was going to use the class native-classe. The basis for placing the class must always be the value of href.

  • 1

    I restored the edited answer

2 answers

1


You can do it this way by scrolling 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 extensions desired in the regex of match by a bar vertical |.

0

A "pitaco" here, I find more succinct:

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.