April 9, 2012

Adding a class via jQuery

Question by Onyx

I have some code dynamically created by Sigma, which looks like this:

<div id="myGrid1_headDiv" class="gt-head-div">
<div class="gt-head-wrap">
<table id="myGrid1_headTable" class="gt-head-table">
<tbody>
<tr class="gt-hd-row">
<td class="gt-col-mygrid1-uid">
<div class="gt-inner gt-inner-left" unselectable="on" title="#">
<span>#</span>
<div class="gt-hd-tool"><span class="gt-hd-icon"></span>
<span class="gt-hd-button"></span>
<span class="gt-hd-split" style="cursor: col-resize; "></span></div></div></td>
<td class="gt-col-mygrid1-p_deldate">
<div class="gt-inner gt-inner-left" unselectable="on" title="Planned Delivery Date">
<span>Planned Delivery Date</span>
<div class="gt-hd-tool"><span class="gt-hd-icon"></span>
<span class="gt-hd-button"></span>
<span class="gt-hd-split" style="cursor: col-resize; "></span></div></div></td>

I am trying to target the un-classed spans( # and Planned Delivery Date), in order to style them, with:

  $("div.gt-inner:first-child span")
    {
          $(this).addClass("celltitle");
        };

but it has no effect. As you can see, there other spans around it that I don’t want to touch. What am I doing wrong?

=====
Final Answer for others using Sigma Grid:

Thanks to @minitech for the pointers, the answer is to add to Sigma Grid’s gridOption with:

onComplete:function(grid){ 
 $('div.gt-inner > span').addClass('celltitle'); //add cell title after grid load
}

Answer by minitech

You’ve inserted an arbitrary code block in there. You need to use jQuery’s .each function and pass your function; jQuery is a library, not a language construct.

$("div.gt-inner:first-child span").each(function() {
    $(this).addClass("celltitle");
});

Or, more concisely, since addClass (like many jQuery functions) implicitly operates on the entire collection:

$('div.gt-inner:first-child span').addClass('celltitle');

Answer by Starx

Use it like this

$("div.gt-inner:first-child span").addClass("celltitle");

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!