admin管理员组文章数量:1415437
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
2 Answers
Reset to default 4Well. 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);
});
});
本文标签: jquerySelect element by tag inside a div with javascriptStack Overflow
版权声明:本文标题:jquery - Select element by tag inside a div with javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745235521a2649019.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论