-5

I have a wrapper element, which contains child elements with unique is's. How does one get the an element without having to traverse?

eg.

<div id="wrapper">
    <div id="child1">content</div>
    <div id="child2">content</div>
    <div id="child3">content</div>
</div>

I am currently using a jQuery.find, but still unable to find only one and first element.

$("#wrapper").find("#child1")......

The code above is not returning the child element specified inside the find function parameter but an array, containing only child1. Thus resulting to write code like this.

$("#wrapper").find("#child1").each(function(){//do something...});

PS: I would really like to avoid something like this as it is inefficient

$("#wrapper #child1")

As I have the #wrapper element already and do not want to traverse over the entire DOM once again.

Paulie
  • 1
  • 2
  • Like this: `$('#wrapper > div:first')` – Yom T. Feb 22 '19 at 09:59
  • 1
    Do you want to find the element `child1`? cant you use something like `$('#wrapper:first-child')` – Carsten Løvbo Andersen Feb 22 '19 at 09:59
  • 1
    Possible duplicate of [How to select first child with jQuery?](https://stackoverflow.com/questions/5852452/how-to-select-first-child-with-jquery) and [How to get the first child id inside the div using JQuery](https://stackoverflow.com/questions/2400076) and [How to Access First Child Div of the Parent Div](https://stackoverflow.com/questions/27043020) – adiga Feb 22 '19 at 10:05
  • 1
    Please read [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Feb 22 '19 at 10:08
  • Please spend some time having a cursory read of the jQuery documentation: https://api.jquery.com Even just reading the method names gives you a good idea of what they do – Rory McCrossan Feb 22 '19 at 10:13
  • Hi RoryMcCrossan. Not just the first element, but every single one of them, without having to traverse. – Paulie Feb 22 '19 at 11:32

4 Answers4

1

If you just want the first element you can use children and refer to the first element

console.log($("#wrapper").children()[0])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="child1">content</div>
  <div id="child2">content</div>
  <div id="child3">content</div>
</div>
ellipsis
  • 12,049
  • 2
  • 17
  • 33
1

If you have the child elements with unique IDs, you can directly access that element by the id.

$("#child1").css('color', 'red');

or if you want to use jQuery, you can make use of the jQuery's children method.

$('#wrapper').children('#child1');
Kumar Aman
  • 271
  • 2
  • 7
0
$("#wrapper div:first-child").css("color","green");
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
PDSSandeep
  • 179
  • 10
-2

You can use :first-child selector

$( "#wrapper:first-child" )
user2935131
  • 157
  • 1
  • 4