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

2
  • You probably don't want that . before the class name. Commented Dec 23, 2014 at 22:08
  • Yes, just a typo error writing the question, edited, thanks:) Commented Dec 23, 2014 at 22:08

2 Answers 2

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');
Sign up to request clarification or add additional context in comments.

Comments

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");

2 Comments

Is it possible to store inside the array the jquery element?
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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.