Note that there are some explanatory texts on larger screens.

plurals
  1. POChanging the color of a selected link that is embedded in a table
    text
    copied!<p>I'm trying to use class names to change the color of a link after it has been selected, so that It will remain the new color, but only until another link is selected, and then it will change back.</p> <p>I'm using this code that was posted by Martin Kool in <a href="https://stackoverflow.com/questions/206689/changing-the-bg-color-of-a-selected-link">this</a> question:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el &amp;&amp; el.className == "unselected") { el.className = "selected"; var siblings = el.parentNode.childNodes; for (var i = 0, l = siblings.length; i &lt; l; i++) { var sib = siblings[i]; if (sib != el &amp;&amp; sib.className == "selected") sib.className = "unselected"; } } } &lt;/script&gt; &lt;style&gt; .selected { background: #f00; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#" class="selected"&gt;One&lt;/a&gt; &lt;a href="#" class="unselected"&gt;Two&lt;/a&gt; &lt;a href="#" class="unselected"&gt;Three&lt;/a&gt; &lt;/body&gt; </code></pre> <p>It works fine until I try to out the links in a table. Why is this? Be easy, I'm a beginner.</p> <hr> <p>There is no error, the links are changing to the "selected" class, but when another link is selected, the old links are keeping the "selected" class instead of changing to "unselected". Basically, as far as I can tell, it's functioning like a vlink attribute, which is not what I'm going for.</p> <p>And yes, the links are all in different cells, how would you suggest I change the code so that it works correctly?</p> <hr> <p>OK, actually, I spoke too soon.</p> <pre><code>document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el &amp;&amp; el.className == 'unselected') { var links = document.getElementsByTagName('a'); for (var i = links.length - 1; i &gt;= 0; i--) { if (links[i].className == 'selected') links[i].className = 'unselected'; } el.className = 'selected'; } return false; } </code></pre> <p>This code you gave me works great, visually, it does exactly what I want it to do. However, It makes my links stop working... They change color, but dont link to anything, and then when I remove the script, they work fine. What am I doing wrong/what do I have to change to make this work?</p> <p>Also, I want to do the same thing somewhere else in my website, where the links are all in one <code>&lt;div&gt;</code> tag, separated by <code>&lt;p&gt;</code> tags. How can I make this work?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload