I have a layout similar to this:
and would like to use a jQuery selector to selec
You can use Child Selecor to reference the child elements available within the parent.
$(' > img', this).attr("src");
And the below is if you don't have reference to $(this)
and you want to reference img
available within a div
from other function.
$('#divid > img').attr("src");
Also this should work:
$("#id img")
If your img is exactly first element inside div then try
$(this.firstChild);
$( "#box" ).click( function() {
let img = $(this.firstChild);
console.log({img});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>
You could use
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(this).find('img');
</script>
The direct children is
$('> .child-class', this)
Here's a functional code, you can run it (it's a simple demonstration).
When you click the DIV you get the image from some different methods, in this situation "this" is the DIV.
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>
Hope it helps!