user2010470
user2010470

Reputation: 21

Select element by tag inside a div with javascript

I have this script which works to show image alt tags.

    $(document).ready(function() {
      $('img').click(function(){
        var altimg = $(this).attr('alt');
        alert('Alt: '+ altimg);
      });
    });

I cant understand the method you would use to specify the element to search within for images (i only want to run this script on images within my content div).

How to implement getElementById in this instance is beyond me, can someone point me in the right direction?

Upvotes: 2

Views: 4386

Answers (2)

Molle
Molle

Reputation: 190

Well. You can find all tag names within an ID by JavaScript with this method.

var x = document.getElementById("divID");
x = x.getElementsByTagName("TAG name to search for") // e.g. "img"

now x[0] will contain the first element with the tag IMG that occurs inside the div. OBS notice the .getElements ByTagName (elements are plural since you can get many, not just 1 like the ...ById method).

With jQuery you can find the images in a way somewhat like CSS

var x = $('#divID').find('img')

If you want to find images only with a specific class name (or something else) then modify the search to this.

var x = $('#divID').find('img').css('class', 'className')

These 2 ways will give you the elements stored as an array in the variable x.

Upvotes: 4

George
George

Reputation: 36794

From what I can understand, you only want this click event to be bound if the image is a child of a specific container (I'll call it #container). Just prepend it to your selector:

$(document).ready(function() {
  $('#container img').click(function(){
    var altimg = $(this).attr('alt');
    alert('Alt: '+ altimg);
  });
});

Upvotes: 2

Related Questions