seleccionar primer parentnode padres obtener nodo los hijos hijo hermano firstchild elemento acceder javascript jquery jquery-selectors this

javascript - primer - ¿Cómo conseguir los hijos del selector $(esto)?



parentnode (16)

Tengo un diseño similar a este:

<div id="..."><img src="..."></div>

y me gustaría usar un selector jQuery para seleccionar el img hijo dentro de la div al hacer clic.

Para obtener el div , tengo este selector:

$(this)

¿Cómo puedo hacer que el niño use un selector?


Aquí hay un código funcional, puede ejecutarlo (es una demostración simple).

Cuando hace clic en el DIV, obtiene la imagen de diferentes métodos, en esta situación "este" es el DIV.

$(document).ready(function() { // When you click the DIV, you take it with "this" $(''#my_div'').click(function() { console.info(''Initializing the tests..''); console.log(''Method #1: ''+$(this).children(''img'')); console.log(''Method #2: ''+$(this).find(''img'')); // Here, i''m selecting the first ocorrence of <IMG> console.log(''Method #3: ''+$(this).find(''img:eq(0)'')); }); });

.the_div{ background-color: yellow; width: 100%; height: 200px; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="my_div" class="the_div"> <img src="..."> </div>

¡Espero eso ayude!


El constructor jQuery acepta un segundo parámetro llamado context que se puede usar para anular el contexto de la selección.

jQuery("img", this);

Que es lo mismo que usar .find() esta manera:

jQuery(this).find("img");

Si las imágenes que desea son solo descendientes directos del elemento pulsado, también puede usar .children() :

jQuery(this).children("img");


Formas de referirse a un niño en jQuery. Lo resumí en el siguiente jQuery:

$(this).find("img"); // any img tag child or grandchild etc... $(this).children("img"); //any img tag child that is direct descendant $(this).find("img:first") //any img tag first child or first grandchild etc... $(this).children("img:first") //the first img tag child that is direct descendant $(this).children("img:nth-child(1)") //the img is first direct descendant child $(this).next(); //the img is first direct descendant child


Los niños directos es

$(''> .child'', this)


Prueba este código:

$(this).children()[0]


Puede tener de 0 a muchas etiquetas <img> dentro de su <div> .

Para encontrar un elemento, use un .find() .

Para mantener su código seguro, use .each() .

El uso de .find() y .each() juntos evita errores de referencia nulos en el caso de 0 elementos <img> y permite el manejo de múltiples elementos <img> .

// Set the click handler on your div $("body").off("click", "#mydiv").on("click", "#mydiv", function() { // Find the image using.find() and .each() $(this).find("img").each(function() { var img = this; // "this" is, now, scoped to the image element // Do something with the image $(this).animate({ width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px" }, 500); }); });

#mydiv { text-align: center; vertical-align: middle; background-color: #000000; cursor: pointer; padding: 50px; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="mydiv"> <img src="" width="100" height="100"/> </div>


Puede usar Child Selecor para hacer referencia a los elementos secundarios disponibles dentro del padre.

$('' > img'', this).attr("src");

Y lo siguiente es si no tiene referencia a $(this) y desea hacer referencia a img disponible dentro de un div desde otra función.

$(''#divid > img'').attr("src");


Puede utilizar cualquiera de los siguientes métodos:

1 encontrar ():

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

2 niños():

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


Puedes encontrar todos los elementos img del div padre como abajo.

$(this).find(''img'') or $(this).children(''img'')

Si quieres un elemento img específico puedes escribir así

$(this).children(''img:nth(n)'') // where n is the child place in parent list start from 0 onwards

Tu div contiene solo un elemento img. Así que para esto abajo está bien.

$(this).find("img").attr("alt") OR $(this).children("img").attr("alt")

Pero si tu div contiene más elementos img como abajo

<div class="mydiv"> <img src="test.png" alt="3"> <img src="test.png" alt="4"> </div>

entonces no puede usar el código superior para encontrar el valor alt del segundo elemento img. Así que puedes probar esto:

$(this).find("img:last-child").attr("alt") OR $(this).children("img:last-child").attr("alt")

Este ejemplo muestra una idea general de cómo puede encontrar un objeto real dentro del objeto principal. Puedes usar clases para diferenciar tu objeto hijo. Eso es fácil y divertido. es decir

<div class="mydiv"> <img class=''first'' src="test.png" alt="3"> <img class=''second'' src="test.png" alt="4"> </div>

Puede hacerlo de la siguiente manera:

$(this).find(".first").attr("alt")

y mas especifico como:

$(this).find("img.first").attr("alt")

Puede utilizar buscar o hijos como código anterior. Para obtener más información, visite Children http://api.jquery.com/children/ y Find http://api.jquery.com/find/ . Ver ejemplo http://jsfiddle.net/lalitjs/Nx8a6/


Si necesita obtener la primera imagen que está bajando exactamente un nivel, puede hacerlo

$(this).children("img:first")


Si su etiqueta DIV es seguida inmediatamente por la etiqueta IMG, también puede usar:

$(this).next();


Sin saber la ID del DIV, creo que podría seleccionar el IMG de esta manera:

$("#"+$(this).attr("id")+" img:first")


También esto debería funcionar:

$("#id img")


También podrías usar

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

que devolvería todos los img s que son descendientes de la div


jQuery each una es una opción:

<div id="test"> <img src="testing.png"/> <img src="testing1.png"/> </div> $(''#test img'').each(function(){ console.log($(this).attr(''src'')); });


$(document).ready(function() { // When you click the DIV, you take it with "this" $(''#my_div'').click(function() { console.info(''Initializing the tests..''); console.log(''Method #1: ''+$(this).children(''img'')); console.log(''Method #2: ''+$(this).find(''img'')); // Here, i''m selecting the first ocorrence of <IMG> console.log(''Method #3: ''+$(this).find(''img:eq(0)'')); }); });

.the_div{ background-color: yellow; width: 100%; height: 200px; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="my_div" class="the_div"> <img src="..."> </div>