I'm trying to "select" a img inside a $(this) selector. I know I can find it by using .find('img')
but is this possible:
$("img",this)
?
What's the most optimal way to do this?
Originally code
<a class="picture" href="test.html">
<img src="picture.jpg" alt="awesome">
</a>
Use the getAttribute() method to check if an image src is empty, e.g. img. getAttribute('src') .
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
Different jQuery SelectorsIt is used to select all elements. It will select all p elements. It will select all h1, div, and p elements.
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
That a perfect reasonably way of doing it.
So you would do like:
$('a').click( function() { //if the element dosent change you can use this //var src = $('img', this).attr('src'); //else use $(this) var src = $('img', $(this)).attr('src'); alert(src); return false; });
See: http://jsfiddle.net/xYmwV/
There is really no difference, since in both methods you load the dom element, and search it. Your way ofcourse is "cleaner" and simpler, but might be more confusing :)
A faster way would be $(this).children()
since it then would'nt have to search for elements, but goes directly downwords in the DOM. But it takes out the flexibility of the script.
What's the most optimal way to do this?
Both $(this).find('img')
and $('img', this)
are equivalent.
From the docs:
Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').
http://api.jquery.com/jQuery/
Yes you can do that... anyway they're equivalent, so it's only a matter of your 'syntactic tastes':
Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').
http://api.jquery.com/jQuery/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With