最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Select element by tag inside a div with javascript - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Jan 22, 2014 at 11:49 Esko 4,2072 gold badges24 silver badges38 bronze badges asked Jan 22, 2014 at 11:45 user2010470user2010470 211 silver badge6 bronze badges 1
  • Apart from the 10 minute delay you have to wait for... – user2010470 Commented Jan 22, 2014 at 13:07
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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);
  });
});
发布评论

评论列表(0)

  1. 暂无评论