flyiinhigh
flyiinhigh

Reputation: 69

How to use jQuery to check for alt attribute

<img src="_images/hockey.png" />    
<img src="_images/himalaya.png" alt="Himalaya Picture"/>

I have the two pictures above in an html File and I want to check if it has an alt attribute or not.

This is my first day learning JQUERY so any help would be greatly appreciated.

Thank you.

Upvotes: 0

Views: 2611

Answers (4)

PeterKA
PeterKA

Reputation: 24638

It all depends on where you are and what you want to do. Here are a few pointers:

  • $('img[alt]') is how in jQuery you select all images with alt attribute. And having selected only those elements you're interested in you can call any one of the jQuery methods that achieves your goal. For instance, add a class to those images: $('img[alt]').addClass('myclass').
  • $('img') is how you select all images. You can call a method such as .each() on this to iterate through each image using the this keyword, then you can check for alt attribute/property on each and perform some action if found. Example:

-

$('img').each(function() {
    if( this.alt ) {
        //do something
    }
});

$('img[alt]').addClass('myclass');
$('img').each(function() {
    console.log( this.alt ? 'HAS ALT' : 'DOES NOT HAVE ALT' );
});
.myclass {
    border: 1px solid blue;
    padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="_images/hockey.png" />    
<img src="_images/himalaya.png" alt="Himalaya Picture"/>

This would be a great read for you: https://stackoverflow.com/tags/jquery/info

Upvotes: 1

Thaillie
Thaillie

Reputation: 1362

You could loop through all images and check for the alt attribute like this

$('img').each(function(i) {
    if ($(this).prop('alt')) {
        console.log($(this).prop('alt') + ' on element ' + i);
    } else {
        //code for when it has no alt
    }
});

In here the i thats given as a variable in the function can be used to select the img from $('img').toArray(). As it is the position of the image on the page (this starts at 0).

Fiddle: https://jsfiddle.net/kezgsgby/

Upvotes: 0

DinoMyte
DinoMyte

Reputation: 8868

Fiddle : http://jsfiddle.net/0qypgs1r/1/

     <img src="_images/hockey.png" />    
        <img src="_images/himalaya.png" alt="Himalaya Picture"/>

  <script> 
        $("img").each(function()
    {
        if($(this).prop("alt"))
            alert($(this).prop("alt"));
    });
</script>

Upvotes: 0

Franklin Satler
Franklin Satler

Reputation: 320

You could select all img elements and filter by "alt" attribute.

$("img[alt]").each(function(){
   console.log($(this));
});

Upvotes: 0

Related Questions