简体   繁体   中英

How to add css to a specific Array element on Jquery

I'm trying to develope a code that generates a random RGB color for each element with the name "Title" on my website.

First, I choose all the elements with a specific class "title" :

var element = $('.title')

Then, I save on a var called n , the total number of titles (used on the for)

var n = element.length

Now. I'm trying to traverse all the title elements and adding by css a random RGB color. Note: I use element[ i ] , to access each of the array element. Is that correct?

for (var i = 0; i < n; i++) {
    element[ i ].css({ 
        "background": randomColor();
    })
}

However it doesn't work... How can I solve that? Any idea.

Regards.

element[i] refers to the dom element which does not have the method css() which is provided by jQuery, so you need to get the jQuery wrapper object for the element at index i which can be obtained by .eq()

for (var i = 0; i < n; i++) {
    element.eq(i).css({ 
        "background": randomColor();
    })
}

You can also pass a function to .css() like

element.css('background', function () {
    return randomColor()
})

What you were doing is almost correct. Except for you didn't create a selector for the i-th element.

$(element[i]) will have the css() function available and would work as expected.

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