0

I have multiple objects with the classname "level1" (this is built on asp.net, the element does not allow setting an ID here)

What I am trying to do is get one of them and assign css properties

$(".level1")[1].css({"background-color":"yellow"});

I get the error

Error: Object doesn't support property or method 'css'

When I do this:

console.log($(".level1")[1].innerHTML);

I get the correct innerHTML, so I know it gets the right element

3 Answers 3

6

Use eq:

$(".level1").eq(1).css({
    "background-color": "yellow"
});

$(".level1")[1] returns the HTML and not the jQuery Object, so you cannot call jQuery method on it. Use eq instead.

eq(1) will get the Second element having class level1(Index starts from 0)

Docs: http://api.jquery.com/eq/

Reduce the set of matched elements to the one at the specified index.

Sign up to request clarification or add additional context in comments.

Comments

0

$(selector)[1] gets the DOM element. To manipulate it again you need the jQuery object:

$($('.level1')[1]).css('background-color', 'yellow');

Edit - see Tushar's answer using .eq()

2 Comments

Doesn't make much sense to use $($('.level1')[1]). You already have a jQuery object there is no need to extract the DOM element and then re-convert it to a jQuery object... However your solution would work :)
@Lix right, Tushar's answer with eq() is the correct way to do this.
0

Make from $(".level1")[1] a jQuery object, because [1] returns HTML DOM element and you need jQuery object for .css() method.

$($(".level1")[1]).css({
    "background-color":"yellow"
});

3 Comments

Doesn't make much sense to use $($('.level1')[1]). You already have a jQuery object there is no need to extract the DOM element and then re-convert it to a jQuery object... However your solution would work :)
@Lix, yes I know, but the best way is to add class, id to element and keep all styles in CSS files or just add :nth-of-type(2) to CSS
In most cases you would be correct, however even changing the class attribute for the element would still require the same sort of selector logic (extracting the element at index N).

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.