How to use addClass with Array selector in JQuery?

3

I need to collect all the elements that have the class "events" in an array, to later traverse the array in search of an attribute, for example, "blablabla". If you have "blablabla", I will add the class "newClass".

I have done the test with a simple script to select only one, and add the class. But I get an error of "addClass is not a function" .

Script:

$(document).ready(function(){
        console.log($(".day-schedule").find(".events")[1].addClass("newClass"));
});

However, if I remove the selector from the array " 1 ", if I include the class in all the elements.

HTML:

<ul>
    <li class="day-schedule"><div>Monday</div>
      <ul class="day">
        <li class="events" atributo"blablabla">
            <span>Hurduring</span>
        </li>
        <li class="events">
            <span>Hurduring</span>
        </li>
        <li class="events" atributo"blablabla">
            <span>Hurduring</span>
        </li>
        <li class="events">
            <span>Hurduring</span>
        </li>
      </ul>
    </li>

    <li class="day-schedule"><div>Wednesday</div>
      <ul class="day">
        <li class="events" atributo"blablabla">
            <span>Hurduring</span>
        </li>
        <li class="events">
            <span>Hurduring</span>
        </li>
        <li class="events" atributo"blablabla">
            <span>Hurduring</span>
        </li>
        <li class="events" atributo"blablabla">
            <span>Hurduring</span>
        </li>
      </ul>
    </li>
</ul>

Jfiddle of the code: Jfiddle URL

    
asked by Lluc Marquès 18.04.2018 в 16:59
source

2 answers

1

When you access the $(".day-schedule").find(".events")[1] index, this returns an HTML element, not a jquery object, and since an html element does not have the addClass method, it throws the error at you.

Use the expression :first to return only the first element found instead of the indexed access:

console.log($(".day-schedule").find(".events:first").addClass("newClass"));

But if you need to access the html element by the index, you can pass the element you want to the jquery function to access the addClass method:

var elemento = $(".day-schedule").find(".events")[1];
console.log($(elemento).addClass("newClass"));
    
answered by 18.04.2018 / 17:01
source
0

To start you have a syntax error in atributo , you need = .

Yours:

<li class="events" atributo"blablabla">

Correct:

<li class="events" atributo="blablabla">

Then, for what you want to do, it's a matter of adding the [atributo=blabla] attribute to the selector, leaving it like this:

$(".day-schedule").find(".events[atributo=blablabla]").addClass("newClass");

I leave you the JSFiddle that you came up with the example working.

    
answered by 18.04.2018 в 17:05