3

I have a function that is called in document.ready() that creates spans.

function configureContentSelector() {
  for (j=0; j<centerContent.length; j++)
    {
        var content = "<span class='contentSelector' onclick='changeContent(" + j + ")' id='span'" + j + ">" + j  + "</span>";
        $("#contentSelectorArea").html($("#contentSelectorArea").html() + content); 

   }

Note the spans are id-ed as span0, span1 etc.

Within a separate function that is called when an event unrelated to the spans is fired I want to manipulate the span classes (addClass() removeClass())

$("#" + "span" + i).removeClass("contentSelector");
$("#" + "span" + i).addClass("contentSelectorSelected");

However, this does not work. I believe this issue is related to the fact that the spans are created dynamically but I do not know how to fix this.

Thanks in advance for any help.

  • once spans are inserted into the DOM you can call `addClass` or `removeClass` on them – Rafay Jul 10 '12 at 16:10
  • What's the function in which you are manipulating the classes? and what is the value of `i` in your add/removeClass? – wirey00 Jul 10 '12 at 16:12

4 Answers4

3

You create wrong ids (all of them have id=span):

var content = "<span class='contentSelector' onclick='changeContent(" + j + ")' id='span'" + j + ">" + j  + "</span>";

Try this:

var content = "<span class='contentSelector' onclick='changeContent(" + j + ")' id='span" + j + "'>" + j  + "</span>";

BTW your quotes should be reversed:

var content = '<span class="contentSelector" onclick="changeContent(' + j + ')" id="span' + j + '">' + j  + '</span>';
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
  • BTW: I thought the order of quotes did not matter (single inside of double or visa versa). – user1515356 Jul 12 '12 at 19:39
  • Well it seems it doesn't really matters ([check this](http://stackoverflow.com/questions/2373074/single-vs-double-quotes-vs)), most times (in my experience) people use `"` in html attributes, so (at least for me) it feels more *natural*. – Zbigniew Jul 13 '12 at 15:10
3

I think there is an error here

id='span'" + j + ">"

change to

id='span" + j + "'>"

and use

$("#contentSelectorArea").append(content);
Marcio Toshio
  • 178
  • 12
2

I would remove the ID and use a data-* attribute (Theres a syntax error with your ID declaration anyway).

var content = "<span class='contentSelector' onclick='changeContent(" + j + ")' data-spanid='" + j + "'>" + j  + "</span>";

Then you can select using the data-* attribute:

$("span[data-spanid='" + i + "']");
Curtis
  • 101,612
  • 66
  • 270
  • 352
1

You have a simple error during the creation of your control. Check the quotes in the id attribute that gets created.

Use this and it'll work fine.

var content = "<span class='contentSelector' onclick='changeContent(" + j + ")' id='span" + j + "'>" + j  + "</span>";
TWickz
  • 622
  • 6
  • 13