Use the :nth-child()
selector, like this:
var elemento = $("#teste div:nth-child(2)");
console.log(elemento.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste">
<div>Teste 1</div>
<div>Teste 2</div> <!-- Quero selecionar esta -->
<div>Teste 3</div>
</div>
The nth-child
is used in CSS too, ie it is not a unique jQuery selector and so it will be available to use pure JavaScript, for example:
var elemento = document.querySelector("#teste div:nth-child(2)");
console.log(elemento.textContent);
<div id="teste">
<div>Teste 1</div>
<div>Teste 2</div> <!-- Quero selecionar esta -->
<div>Teste 3</div>
</div>
The :nth-child
can select by the order of the child, 1, 2, 3, 4, and so on. It can also select more than one element as only odd or even elements, for example:
-
:nth-child(2n+1)
will select only the odd child elements
-
:nth-child(2n)
will select only the child elements even
To go deeper just adjust the children of the selector, use the #teste > div > img:nth-child(<posição do filho>)
selector for this:
var elemento = $("#teste > div > img:nth-child(2)");
console.log(elemento.attr("src"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste">
<div>Teste 1</div>
<div>
<img src="esta_nao.jpg" />
<img src="teste_teste.jpg" /> <!-- Quero selecionar esta -->
</div>
</div>
Or you can get the src attribute of the image:
var elemento = $("#teste > div > img[src=teste_teste.jpg]");
console.log(elemento.attr("src"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste">
<div>Teste 1</div>
<div>
<img src="esta_nao.jpg" />
<img src="teste_teste.jpg" /> <!-- Quero selecionar esta -->
</div>
</div>
If you want to get images that end with teste_teste.jpg
use "#teste > div > img[src$=teste_teste.jpg]"
, for example this would be taken too:
<img src="/foo/bar/teste_teste.jpg" />
Because the $
pendent will get everything ending in teste_teste.jpg
Note: selector >
is used to indicate that the element must be a child of the previous selector, so here #teste > div > img
:
-
<img>
must be the direct child of <div>
-
<div>
must be direct child of <(elemento) id="teste"></(elemento)>
-
used (elemento)
because #
without indicated element says that any element that contains the id
can have the baby > div
below, it is clear that the attribute id=
can never be repeated in HTML