0
<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.

flyiinhigh
  • 69
  • 1
  • 10
  • https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=jquery+check+attribute+exists – AmmarCSE Sep 16 '15 at 22:28
  • 4
    possible duplicate of [jQuery hasAttr checking to see if there is an attribute on an element](http://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element) – Starfish Sep 16 '15 at 22:29

4 Answers4

1

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

Community
  • 1
  • 1
PeterKA
  • 24,158
  • 5
  • 26
  • 48
0

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

$("img[alt]").each(function(){
   console.log($(this));
});
Franklin Satler
  • 320
  • 1
  • 7
0

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>
DinoMyte
  • 8,737
  • 1
  • 19
  • 26
0

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/

Thaillie
  • 1,362
  • 3
  • 17
  • 31