Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(this +"selector") ? $("img",this) possible?

Tags:

jquery

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>
like image 825
Plexus81 Avatar asked Apr 17 '12 07:04

Plexus81


People also ask

How do I know if my IMG has an SRC?

Use the getAttribute() method to check if an image src is empty, e.g. img. getAttribute('src') .

How do you get the children of the $( this selector?

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.

What does the selector $( Div?

Different jQuery SelectorsIt is used to select all elements. It will select all p elements. It will select all h1, div, and p elements.

Can we use multiple selectors in jQuery?

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.


3 Answers

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.

like image 35
Marco Johannesen Avatar answered Sep 25 '22 07:09

Marco Johannesen


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/

like image 161
Andreas Wong Avatar answered Sep 23 '22 07:09

Andreas Wong


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/

like image 38
mamoo Avatar answered Sep 24 '22 07:09

mamoo