-1

I want to be able to remove a class from x amount of elements. The elements that I am currently using is a tags. There can be unlimited amount of a tags on the document at any given time because in a different div an user can create links. This prevents me from using specific ids. But I want to only have one tag highlighted at any given time. However, I have only seen how to do it with JQuery, which I can't use. I saw a different example using Javascript, but that was for a fixed size array.

This is the code for my highlighting class:

<DOCTYPE html>
<html>
   <head>
<style>
    .selected{border:dotted 2px;border-color:gray;}
</style>
</head>
<body>
<div id='linkEditDiv'>
         <form name='linkEditor'>
           <table>
             <input type="hidden" name='linkId'>
             <tr><th>Label:</th><td> <input type='text'  name='label'></td></tr>
             <tr><th>Link:</th><td> <input type='text' name='link'></td></tr>
             <tr><th></th><td><input type="button" onclick='submitForm()' value="OK" ><input type="button" onclick='cancel()' value="Cancel" ></td></tr>
            </table>
         </form>
      </div>
    <a href='#' onclick='edit("lr1")' id='lr1'>link1</a>
 <a href='#' onclick='edit("lr2")' id='lr2'>link1</a>
 <a href='#' onclick='edit("lr3")' id='lr3'>link1</a>
</body>
</html>

This is the JavaScript that adds the highlighting:

 function edit(link)
    {

        var elems = document.getElementsByClassName('selected');
        for (var i = 0; i < elems.length; i++) {
    elems[i].className = elems[i].className.replace('selected', '')
}
        document.getElementById(link).className += "selected"
    }

This is the JavaScript that I tried:

    var id=document.forms['linkEditor'].elements['linkId'].value;
    document.getElementById(id).className = document.getElementById(id).className.replace( /(?:^|\s)selected(?!\S)/g , '' );
user3499265
  • 97
  • 1
  • 9
  • 1
    Please post your HTML and the JavaScript you tried. – j08691 Aug 08 '14 at 15:21
  • Why can't you use jQuery? – Spencer Wieczorek Aug 08 '14 at 15:24
  • 1
    Take a look at the [`getElementsByTagName`](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) method, as well as the [`className`](https://developer.mozilla.org/en-US/docs/Web/API/Element.className) property. If you attempt a solution with those tools, and you're still unable to solve the problem, then it's appropriate to seek help here. – nbrooks Aug 08 '14 at 15:24
  • 1
    read this post: http://stackoverflow.com/questions/2155737/remove-css-class-from-element-with-javascript-no-jquery – The One and Only ChemistryBlob Aug 08 '14 at 15:25
  • I can't use that solution, an user can create any number links at any one time – user3499265 Aug 08 '14 at 15:27
  • In your `getElementById(id)` do you have a variable named `id` somewhere? – j08691 Aug 08 '14 at 15:27

3 Answers3

2

Create a removeClass function that iterates over the elements and replaces the class with an empty string, thus removing it.

function removeClass(selector, klass) {
    var elems = document.querySelectorAll(selector);

    for (var i = elems.length; i--;) {
        var reg = new RegExp("(?:^|\\s)"+ klass +"(?!\\S)", "gi");
        elems[i].className = elems[i].className.replace(reg, "");
    }
}

to be used as

removeClass('.classname', 'classToRemove');

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

First you grab all selected nodes, you loop through them and then you remove the class from each node.

You can't use getElementsByClassName because once you remove the class from the first element, the live dom object updates and shifts the positions, which will lead to moving the for loop one position and skipping that element.

for (const node of document.querySelectorAll('.selected')) {
  node.classList.remove('selected')
}
.selected {
  color: red
}
<p class="selected">Red text</p>
<p class="selected">Red text</p>
<p>Black text</p>
dreamLo
  • 1,612
  • 12
  • 17
0

Try something like this to remove the class from all of the links, and then add the "selected" class back onto the link that you want to have it:

var elems = document.getElementsByClassName('selected');
for (var i = 0; i < elems.length; i++) {
    elems[i].className = elems[i].className.replace('selected', '')
}

UPDATE: Just to clarify, the code works in the form you have in the question. I have taken it and applied two tweaks. 1) The hidden input should not be inside the table tags but outside of td/th tags. 2) I added "return false;" to the links.

<DOCTYPE html>
<html>
    <head>
        <style>.selected{border:dotted 2px;border-color:gray;}</style>
        <script>
            function edit(link) {
                var elems = document.getElementsByClassName('selected');
                for (var i = 0; i < elems.length; i++) {
                    elems[i].className = elems[i].className.replace('selected', '')
                }
                document.getElementById(link).className += "selected"
            }
        </script>
    </head>
    <body>
        <div id='linkEditDiv'>
            <form name='linkEditor'>
                <input type="hidden" name='linkId'>
                <table>
                    <tr><th>Label:</th><td> <input type='text'    name='label'></td></tr>
                    <tr><th>Link:</th><td> <input type='text' name='link'></td></tr>
                    <tr><th></th><td><input type="button" onclick='submitForm()' value="OK" ><input type="button" onclick='cancel()' value="Cancel" ></td></tr>
                </table>
            </form>
        </div>

        <a href='#' onclick='edit("lr1"); return false;' id='lr1'>link1</a>
        <a href='#' onclick='edit("lr2"); return false;' id='lr2'>link1</a>
        <a href='#' onclick='edit("lr3"); return false;' id='lr3'>link1</a>
    </body>
</html>

This is no longer the issue that you were asking for help with.

EpicVoyage
  • 604
  • 7
  • 20
  • This doesn't work. It keeps one highlighted when it shouldn't. It also prevents one from being highlighted – user3499265 Aug 08 '14 at 15:35
  • Can we see how you are using the code? I tested this here on SO before posting and it removed all of the classes that I requested. – EpicVoyage Aug 08 '14 at 15:36
  • While reviewing the JS snippet next to the HTML, I see that your onclick= attributes do not have closing quote marks. That is very likely to cause the web browser to mis-interpret the id= attribute. Once those are fixed, everything seems to work: http://jsfiddle.net/Pegleg3941/295zhkrj/ – EpicVoyage Aug 08 '14 at 15:52
  • in my actual code, they do have it. In my haste of retyping it here, i forgot them – user3499265 Aug 08 '14 at 15:55
  • Updated my answer with a full example, using your code. – EpicVoyage Aug 08 '14 at 16:11
  • This doesn't work because after you remove the class from the first element, the array shifts, and will skip the next element. You need to use `querySelectorAll` – dreamLo Feb 04 '22 at 15:12
  • `getElementsByClassName` does return a live HTMLCollection, which could change depending on what changes you make. In my testing, I have not seen items disappear in this loop with class names but some changes may cause that to happen. – EpicVoyage Feb 04 '22 at 16:46