Search code examples
javascriptjqueryhtmlcss

How to find img with a certain src url and change css using vanilla javascript?


I want to try find an image that has a src that starts with a particular path and change its css properties with vanilla js. Assume I don't have access to its id o class.

Here's something similar using jquery:

$("img").each(function(i, elem){
  if ($(this).attr("src") == "http://googl"){
    $(this).css('display','none');
  }
});

Solution

  • You dont need js or jquery for this - use the CSS attribute selector and hide the image based on the src attribute matching the target text. Note the syntax of the selector to match the src attribute value which is any text preceded by "https://www.google"

    img[src ^= "https://www.google"]{
      display: none;
    }
    <img src="https://www.google.com/url?sa=i&source=images&cd=&ved=2ahUKEwi39tv6xerjAhUPfysKHYwUBfIQjRx6BAgBEAU&url=https%3A%2F%2Fweheartit.com%2Fentry%2F230207975&psig=AOvVaw2PDSxeoivmwsXMXWxVICIQ&ust=1565053762473751" alt="google-image"  title="google-image" />
    <img src="https://via.placeholder.com/100x150" alt="not google-image"   title="not google-image" />