Use the selector :nth-child()
, thus:
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>
<div id="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 is not a unique jQuery selector and so will be available for using 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 son’s order, 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 paired child elements
To go deeper just adjust the children of the selector, use the selector #teste > div > img:nth-child(<posição do filho>)
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>
<div id="teste">
<div>Teste 1</div>
<div>
<img src="esta_nao.jpg" />
<img src="teste_teste.jpg" /> <!-- Quero selecionar esta -->
</div>
</div>
Or you can take by 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>
<div id="teste">
<div>Teste 1</div>
<div>
<img src="esta_nao.jpg" />
<img src="teste_teste.jpg" /> <!-- Quero selecionar esta -->
</div>
</div>
If you wish to take pictures that end with teste_teste.jpg
use "#teste > div > img[src$=teste_teste.jpg]"
, for example this would be caught too:
<img src="/foo/bar/teste_teste.jpg" />
For the dollar sign $
will take everything that ends in teste_teste.jpg
Note: the selector >
serves to indicate that the element must be child direct from the previous selector, so here #teste > div > img
:
<img>
shall be the direct child of <div>
<div>
shall be the direct child of <(elemento) id="teste"></(elemento)>
-
used (elemento)
because the #
without an element indicated, it says that any element containing the id
can have the child > div
then of course the attribute id=
can never be repeated in HTML
You used
div::nth-child(3)
, but it’s only one:
, then it should bediv:nth-child(3)
– Guilherme Nascimento