Jquery как найти первого дочернего элемента

first-child selector

Description: Selects all elements that are the first child of their parent.

  • version added: 1.1.4jQuery( «:first-child» )

While .first() matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

Example:

Finds the first span in each matched div to underline and add a hover state.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

<title>first-child demo</title>

<script src="https://code.jquery.com/jquery-3.7.0.js"></script>

$( "div span:first-child" )

.css( "text-decoration", "underline" )

$( this ).addClass( "sogreen" );

$( this ).removeClass( "sogreen" );

Demo:

In plain JavaScript you would use something like:

// Single
document.querySelector(".onediv").classList.add("red"); 

// Multiple (deeply nested)
document.querySelectorAll(".onediv:first-child").forEach(EL => EL.classList.add("red"));

Or by Parent Element using Element.firstElementChild:

// Single Parent 
document.querySelector(".alldivs").firstElementChild.classList.add("red");

// Multiple parents
document.querySelector(".alldivs").forEach(EL => EL.firstElementChild.classList.add("red"));

jQuery get first child

Use: $(".onediv").eq(0)

Other examples of selectors and methods targeting the first LI inside an UL:

There are some slight differences in how they operate regarding depth. Play with the below demo examples:

$("select").on("change", function() {
  $("li").removeClass("red");
  new Function(`return (${this.value})`)();
}).trigger("change");
.red {color: red;}
option[disabled] {font-size: 1.4em; color: blue;}
<select>
  <option disabled>jQuery examples:</option>

  <option>$("li").eq(0).addClass("red")</option>
  <option>$("li:eq(0)").addClass("red")</option>
  <option>$("li").first().addClass("red")</option>
  <option>$("li:first").addClass("red")</option>
  <option>$("li:first-child").addClass("red")</option>
  <option>$("li:lt(1)").addClass("red")</option>
  <option>$("li:nth-child(1)").addClass("red")</option>
  <option>$("li").slice(0,1).addClass("red")</option>

  <option disabled>JavaScript examples:</option>

  <option>document.querySelector("li").classList.add("red")</option>
  <option>document.querySelectorAll("li:first-child").forEach(EL => EL.classList.add("red"))</option>

  <option disabled>Mixed jQuery + JavaScript</option>

  <option>$("li")[0].classList.add("red")</option>
</select>

<ul>
  <li>1</li>
  <li>2
    <ul>
      <li>2.1</li>
      <li>2.2</li>
    </ul>
  </li>
  <li>3</li>
</ul>

<script src="https://code.jquery.com/jquery-3.6.0.js"></script>

you can also use [i] to get the JS Element by index out of the jQuery elements collection like eg:

$("li")[0]

but now that you have the native JS Element representation you have to use JavaScript methods eg:

$("li")[0].classList.add("active"); // Adds class "active" to the first LI in the DOM

or you can (don’t — it’s bad design) wrap it back into a jQuery object

$( $("li")[0] ).addClass("active"); // Don't! Use .eq() instead

Using jQuery how do I select a single child element? I’ve looked at the Traversing API and know I can select all the immediate children img elements like this:

$(this).children('img');

And to select the first child img element I could use a subscript like this:

$(this).children('img')[0];

But I guess I’m kind of surprised I can’t do this:

$(this).child('img'); // no subscript, returns single element

Or have I missed something?

Kevin Ji's user avatar

Kevin Ji

10.4k4 gold badges40 silver badges62 bronze badges

asked Sep 24, 2009 at 20:52

Jonathon Watney's user avatar

Jonathon WatneyJonathon Watney

19.8k9 gold badges37 silver badges40 bronze badges

I think what you want to do is this:

$(this).children('img').eq(0);

this will give you a jquery object containing the first img element, whereas

$(this).children('img')[0];

will give you the img element itself.

answered Sep 24, 2009 at 20:57

Greg's user avatar

2

No. Every jQuery function returns a jQuery object, and that is how it works. This is a crucial part of jQuery’s magic.

If you want to access the underlying element, you have three options…

  1. Do not use jQuery
  2. Use [0] to reference it
  3. Extend jQuery to do what you want…

    $.fn.child = function(s) {
        return $(this).children(s)[0];
    }
    

Kevin Ji's user avatar

Kevin Ji

10.4k4 gold badges40 silver badges62 bronze badges

answered Sep 24, 2009 at 21:02

Josh Stodola's user avatar

Josh StodolaJosh Stodola

81.3k47 gold badges180 silver badges227 bronze badges

3

Maybe in this way?

$('img', this)[0]

Nakilon's user avatar

Nakilon

34.9k14 gold badges107 silver badges142 bronze badges

answered Sep 24, 2009 at 20:58

Anatoliy's user avatar

AnatoliyAnatoliy

29.4k5 gold badges44 silver badges45 bronze badges

1

You can target the first child element with just using CSS selector with jQuery:

$(this).children('img:nth-child(1)');

If you want to target the second child element just change 1 to 2:

$(this).children('img:nth-child(2)');

and so on..

if you want to target more elements, you can use a for loop:

for (i = 1; i <= $(this).children().length; i++) {
    let childImg =  $(this).children("img:nth-child("+ i +")");
    // Do stuff...
}

answered Nov 20, 2020 at 23:22

Ahmed Khaber's user avatar

Not jQuery, as the question asks for, but natively (i.e., no libraries required) I think the better tool for the job is querySelector to get a single instance of a selector:

let el = document.querySelector('img');
console.log(el);

For all matching instances, use document.querySelectorAll(), or for those within another element you can chain as follows:

// Get some wrapper, with class="parentClassName"
let parentEl = document.querySelector('.parentClassName');
// Get all img tags within the parent element by parentEl variable
let childrenEls = parentEl.querySelectorAll('img');

Note the above is equivalent to:

let childrenEls = document.querySelector('.parentClassName').querySelectorAll('img');

sidoco's user avatar

answered Feb 22, 2019 at 9:13

Nick Bull's user avatar

Nick BullNick Bull

9,4476 gold badges32 silver badges58 bronze badges

<html>
<title>

    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>




<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
 <!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->

<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>




</asp:Repeater>


</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>

<script>

 $(function () {
        $('a').click(function() {
            $(this).parent().children('.dataContentSectionMessages').slideToggle();
        });
    });

    </script>


</html>

answered Aug 23, 2017 at 14:53

Shashank Malviya's user avatar

1

В jQuery есть способ быстро найти первый дочерний элемент любого элемента. Делается это при помощи метода .find(selector) и передачи в него параметра ":first-child".

Пример first-child

Есть список <ul>, в котором нужно найти первый элемент <li>

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=»Content-Type» content=»text/html; charset=utf-8″>
<title>firstChild (jQuery)</title>

<script type=»text/javascript» src=»/js/jquery/jquery.js»></script>

<script type=»text/javascript»>
$(document).ready(function(){
var firstChildText = $(‘#list’).find(‘:first-child’).text();

document.writeln(firstChildText); // Первое значение
});
</script>

</head>

<body>

<ul id=»list»>
<li>Первое значение</li>
<li>Второе значение</li>
<li>Третье значение</li>
<li>Четвертое значение</li>
<li>Пятое значение</li>
<li>Шестое значение</li>
<li>Седьмое значение</li>
</ul>

</body>
</html>

нет оценок

Категории

ПрограммированиеJavaScriptБиблиотекиjQuery

Читайте также

  • lastChild (jQuery)
  • Последний элемент списка (jQuery)
  • Элемент по атрибуту (jQuery)
  • Поиск по классу (jQuery)
  • Медленно удалить элемент (jQuery)
  • Select selected text (jQuery)
  • Поиск по двум классам (jQuery)
  • Координаты элемента (jQuery)
  • fadein (jQuery)
  • Анимированный скролл до элемента (jQuery)
  • Загрузка страниц (jQuery)
  • ready (jQuery)

Комментарии

Перейти к содержимому

Методы jQuery children и find позволяют получить коллекции дочерних элементов. Их отличие в том, что children смотрит только прямых потомков, а find заходит глубже по иерархии, смотря потомков от потомков и т. д.

Синтаксис:

var childs1 = $(selector1).children(childselector);

var finds1 = $(selector1).find(findselector);

Здесь childselector и findselector — это необязательные параметры. С их помощью можно отфильтровать дочерние элементы. Можно вызывать без них:

var childs1 = $(selector1).children();

var finds1 = $(selector1).find();

Приведу пример. Пусть у нас есть HTML-страница со следующим содержимым:

...

<div id=«myparentdivid»>

    <div id=«mychilddivid1»>

    </div>

    <div id=«mychilddivid2»>

        <div id=«mychilddivid3»>

        </div>

    </div>

</div>

...

Код, приведённый ниже, добавит текст «text1» в div с id=»mychilddivid1″, и текст «text2» в div с id=»mychilddivid3″.

$(«#myparentdivid»).children(«#mychilddivid1»).text(«text1»);

$(«#myparentdivid»).find(«#mychilddivid3»).text(«text2»);

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как составить командировочное письмо
  • Как найти свой тариф на мегафоне
  • Как найти обрыв датчика абс
  • Как составить график уборки помещений образец в доу
  • Нашел сережку как сдать

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии