简体   繁体   中英

Get element by class at given index

I've got html looking like this:

<main>
    <div class="list">
        <div class="newdiv">
            <input type="text" class="stuff ind">
            <button class="delete">Delete</button>
            <button class="add">Add</button>
            <div class="start ind">0</div>
            <div class="creation-time ind">0</div>
            <div class="priv ind">0</div>
        </div>
    </div>
</main>

Some of the elements have additional class 'ind'. And my question is there a way in which I could access those elements by their class and index? For example, I want to get a third element with 'ind' class. I've tried things like $('.list').find('.ind').eq(3) but with no luck.

This snippet is using .toArray() method.

  • Once all .ind s are in an array named indArray it is sent through a for loop.
  • On each iteration (loop), a .ind will be assigned text that corresponds to their own index.
  • On each iteration a .ind will have red text.
  • On the first .ind ( indArray[0] ) since it's an input and not a div, it's number is set by .value instead of .innerHTML .

So as an array of .ind s, you now have easy access by index and class. If you wanted to select the third .ind to have a pink background:

  • indArray[2].style.backgroundColor = "pink";

Note: You're probably already aware that arrays are zero based so indArray[2] is the third element of the array.

Snippet

 $(function() { var indArray = $('.ind').toArray(); for(var i = 0; i < indArray.length; i++) { indArray[i].innerHTML = i; indArray[i].style.color = "red"; if(i === 0) { indArray[i].value = i; } } }); 
 main { border: 4px dotted black; background: rgba(0, 0, 0, .3); } div { border: 1px dashed blue; background: rgba(255, 255, 255, .3); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <main> <div class="list"> <div class="newdiv"> <input type="text" class="stuff ind"> <button class="delete">Delete</button> <button class="add">Add</button> <div class="start ind">0</div> <div class="creation-time ind">0</div> <div class="priv ind">0</div> </div> </div> </main> 

原始的$('.list').find('.ind').eq(3)应该可以很好地完成您想做的事情(您确定jQuery正确加载了吗?),或者是$('.list .ind').eq(3)也可以工作(尽管效率较低)。

I was able to get it using a compound CSS selector and then grabbing the 3rd element in the array. So $('.list .ind').eq(2);

Here it is working in JS Bin: https://jsbin.com/cirikapewi/edit?html,js,output

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