elemento de la lista de destino en jquery

I have a list and I'm checking if the list item has two specific classes. If it does, I want to change the background of that list item to blue. however my code doesn't seem to work. How can I target that specific list item? The alert works fine, it's just the colour which doesn't.

if (($("#all-colls-list li:contains(" + itemName + ")").hasClass("groupAdded")) && ($("#all-colls-list li:contains(" + itemName + ")").hasClass("selAdded")) ) {
                $(this).css("background-color", "blue");
                alert("has both classes");
            }

preguntado el 31 de julio de 12 a las 11:07

3 Respuestas

Usar selectores de clases en lugar de hasClass () will allow you to achieve what you're looking for with a single selector, and to obtain references to the elements you want to modify:

$("#all-colls-list li:contains(" + itemName + ").groupAdded.selAdded")
    .css("background-color", "blue");

Respondido 31 Jul 12, 11:07

$("#all-colls-list li:contains(" + itemName + ")").each(function(){
    if ($(this).hasClass("groupAdded") && $(this).hasClass("selAdded")) {
        $(this).css("background-color", "blue");
    }
})

Respondido 31 Jul 12, 11:07

que $(this) is probably undefined since your accessing that element directly in the if above. Calling all the selector again in the .css function should solve your problem

if (($("#all-colls-list li:contains(" + itemName + ")").hasClass("groupAdded")) && ($("#all-colls-list li:contains(" + itemName + ")").hasClass("selAdded")) ) {
                    $("#all-colls-list li:contains(" + itemName + ")").css("background-color", "blue");
                    alert("has both classes");
                }

Respondido 31 Jul 12, 11:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.