0

I've just started using jQuery, but am a bit stuck. I am building a table dynamically in Javascript and am adding classes all the time to cells (for styling), so I would like to use the addClass function:

var row = table.insertRow(-1);
var cell = row.insertCell(0);
cell.addClass('boldRow');

but this does not work. I know you can use the magic $('') function to be able to use jQuery, but can I use it on 'native' HTMLElement references?

5 Answers 5

3

$(cell).addClass should do the trick - why don't you try it and let us know.

In any case you have to use the $() to load the jQuery framework to get access to addClass.

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

3 Comments

Thanks, I didn't realise you could pass DOM objects as well as strings.
No problem, jQuery tends to pleasantly surprise like that :)
Yes, it has restored my faith in javascript.
1

You just place the element in like you would a string.

$(someElementReference).addClass('boldrow');

You can also pass in a collection of elements if that is what you have.

Here's an example: http://jsfiddle.net/qS473/

1 Comment

@Callum - Yeah, it's pretty handy. Lots of settings on the left to do things like load different libraries.
1

Yes, you can pass in native DOM objects into the jQuery function, and it will create a jQuery object from the DOM object:

$(cell).addClass('boldRow');

But you don't need jQuery to add a CSS class to a DOM object!:

cell.class += ' boldRow';

2 Comments

I know - I'm doing that at the moment :) But it is very annoying to do that each time, and this is very complex table. Thanks anyway.
Jacob - Don't forget to fix your DOM API version for IE6. :o)
0

Yes, you can select all HTML elements with $() for example, $('body'), or $('html') etc. Since it's only a framework, you can also use any other Javascript you can think of to fix this.

Comments

0

Usually the first thing I do when creating a new element is something like this:

var newDivJQObject = $(document.createElement('div'))
  .attr('id', '[uniqueID]')
  .addClass('[className]');

Comments

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.