views:

37

answers:

5

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?

+3  A: 

$(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.

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

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/

patrick dw
That's a great website +1
Callum Rogers
@Callum - Yeah, it's pretty handy. Lots of settings on the left to do things like load different libraries.
patrick dw
+1  A: 

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';
Jacob Relkin
Of course not - but the jQuery version is so much better :)
Justin Ethier
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.
Callum Rogers
Jacob - Don't forget to fix your DOM API version for IE6. :o)
patrick dw
A: 

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.

Calle
A: 

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]');
JoshNaro