How can I use JQuery to select the first div eleme

2019-09-16 21:19发布

问题:

I am pretty new in JQuery and I have the following situation:

<!-- Bottone relativo ai progetti WIFI: -->
<a title="WIFI" href="javascript: void(0)" id="showWifi_${item.index}" class="showWifi">
    <div class="news_box news_box_01 hvr-underline-from-center " style="margin-right: 50px;"></div>
</a>

I have the a tag having class="showWifi".

I have to use JQuery to select the first div element inside this a tag having class="showWifi".

I don't want set an id to this tag, but I want use the JQuery syntax to select the first div tag

How can I do this?

回答1:

You can use first()

$('a.showWifi div').first().addClass('something')

You can also use :first pseudo-selector

$('a.showWifi div:first').addClass('something')

Note: first() is faster than :first(Thanks to @Zeratops). See: jQuery :first vs. .first()



回答2:

You can use :first

Selects the first matched element.

$('a.showWifi > div:first')


回答3:

Use .first()

$(".showWifi").find("div").first();

Working JSFIDDLE: http://jsfiddle.net/uamkvdkr/