addClass to element inside an array
Asked Answered
P

2

5

can you help me understand why this is not working?

var elementTab1 = $('#tab1 .item-media.modificato');
elementTab1[0].addClass('selezionato');

this through this error

TypeError: undefined is not a function (evaluating 'elementTab1[0].addClass('selezionato')')

Thanks

Pirouette answered 23/12, 2014 at 22:3 Comment(2)
You probably don't want that . before the class name.Open
Yes, just a typo error writing the question, edited, thanks:)Pirouette
J
7

elementTab1 is already a jQuery object. It contains an array of matched elements in the DOM. Accessing the first index using [0] will return a native element with access to the native JavaScript API (and not jQuery's).

jQuery does provide a nice way to grab items from the array though. It is .eq().

elementTab1.eq(0).addClass('selezionato');
Jeroboam answered 23/12, 2014 at 22:36 Comment(0)
F
6

Accessing an element of a JQuery object (via your elementTab1[0]) call returns the DOM element, not a JQuery element.

DOM elements do not have an .addClass method.

The following code should work for you:

$(elementTab1[0]).addClass(".selezionato");

Alternately, just skip JQuery and use the native DOM APIs:

document
   .querySelector("#tab1 .item-media.modificato")
   .classList
   .add(".selezionato");
Frizzell answered 23/12, 2014 at 22:5 Comment(2)
Is it possible to store inside the array the jquery element?Pirouette
No, JQuery stores the DOM elements in the array-like object it returns to you. Truth be told, you don't really need JQuery for any of this. Just use the native HTML DOM APIs: document.querySelector("#tab1 .item-media.modificato").classList.add(".selezionato")Frizzell

© 2022 - 2024 — McMap. All rights reserved.