title: Add CSS rule via jQuery for future created elements
body: <p>I have a somewhat unusual issue. I've done something like this many times:</p>
  
  <pre><code>$('#selector').css('color','#00f');
  </code></pre>
  
  <p>My problem is that I create a <code>&lt;div id="selector"&gt;</code>, and I call the command above and it works fine.</p>
  
  <p>Now, on another event, later, I remove that element from the <a href="http://en.wikipedia.org/wiki/Document_Object_Model" rel="noreferrer">DOM</a> and add it again at a later time with the same id. This element now doesn't have <code>color:#00f</code>.</p>
  
  <p>Is there a way that I can add a rule in CSS, such that it will affect items that are created in the future with that same <code>id</code>/<code>class</code>? I like <a href="http://en.wikipedia.org/wiki/JQuery" rel="noreferrer">jQuery</a>, but anything with plain JavaScript would be fine as well.</p>
  
  <p>It has to be dynamic, and I don't know the classes to put in a CSS file.  Also, I plan on changing a single attribute a few different times through the course of the application. For example, setting the <code>color</code> to <code>black</code>, to <code>blue</code>, to <code>red</code>, and back to <code>black</code>.</p>
  
  <p><br/></p>
  
  <hr/>
  
  <p>I went with the answer from <strong>@lucassp</strong>, and this is what I ended up with:</p>
  
  <pre><code>function toggleIcon(elem, classname)
  {
      if($(elem).attr('src')=='img/checkbox_checked.gif')
      {
          $(elem).attr('src', 'img/checkbox_unchecked.gif')
          //$('.'+classname).hide();//this was the old line that I removed
          $('html &gt; head').append($('&lt;style&gt;.'+classname+' { display:none; }&lt;/style&gt;'));
      }
      else
      {
          $(elem).attr('src', 'img/checkbox_checked.gif')
          //$('.'+classname).show();//this was the old line that I removed
          $('html &gt; head').append($('&lt;style&gt;.'+classname+' { display:block; }&lt;/style&gt;'));
      }
  }
  </code></pre>
  
  <p>I also want to say that <strong>@Nelson</strong> is probably the most "correct", though it would require more work to go into application code that always works fine, and that's not effort I want to spend at the moment.</p>
  
  <p>If I had to rewrite this (or write something similar) in the future, I would look into <code>detach()</code>.</p>