简体   繁体   中英

jquery - get div from a li

I am new in javascript/jquery. I am trying to select from a li element a div in wich i will put 3 images. So I have this variable:

var x = ui.item.parent().children()[i]

Which is the li (it works, i've check the id), but how can I get the div from x ? (and after that all 3 images so i can change the z-index of the images, which i also don't know how).

<ul>
   <li id="li1">
   <div>
       <img class="1" src="img1.jpg" style="position:absolute;z-index=1">
       <img class="2" src="img2.jpg" style="position:absolute;z-index=2">
       <img class="3" src="img3.jpg" style="position:absolute;z-index=3">
   </div>
   </li>
</ul>

This is the code i write, but is not working (error: Uncaught TypeError: Object # has no method 'find' )

for(var i=0;i<ui.item.parent().children().length-4;i++){
    var x =ui.item.parent().children()[i];
    x.find('img').css('z-index', '2');  
                }

Please correct your html. Your ul ends before you li does. Once you have a jQuery element, you can use the .find() function to search its childs.

For example:

var x = $('li#yourid');

x.find('img').css('z-index', '2');

your HTML is not valid, you're closing the li tag after the ul and the li do not have the open tag < .

So correct HTML is:

<ul>
<li id="li1">
<div>
<img class="1" src="...">
<img class="2">
<img class="3">
</div>
</li>
<ul>

Now to get the div from x you need to use .find() :

var div = x.find('div');

Use like this

$("ul li").children("div").find("img").each(function(){
     alert($(this).attr('class'));
});

See Demo

I don't know if that HTML is just an example, but it's not correctly formatted. It should be:

<ul>
    <li id="li1">
        <div>
            <img class="1" src="..."/>
            <img class="2"/>
            <img class="3"/>
        </div>
    </li>
</ul>

To set the z-index: $(x).find('img').css('z-index','100');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM