Search code examples
jqueryaddclassremoveclass

jQuery first: selector not working after function run once


When the key down function runs the first time it does what I expect and changes the first class to addBack. Every keypress after that has no effect. html displayed below is after 1 keypress.

html:

 <h1 id="id1">
    <span class="addBack">H</span>
    <span class="noBack">E</span>
    <span class="noBack">L</span>
    <span class="noBack">L</span>
    <span class="noBack">O</span>
 </h1> 

jQuery:

    inputBox.keydown(function() {
    $("span.noBack:first").removeClass("noBack").addClass("addBack");
    });

Solution

  • Original answer

    Seems to work for me just fine:

    $('#inputBox').keydown(function() {
        $("span.noBack:first").removeClass("noBack").addClass("addBack");
        });
    .addBack { color: green; }
    .noBack {color: red;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <h1 id="id1">
        <span class="addBack">H</span>
        <span class="noBack">E</span>
        <span class="noBack">L</span>
        <span class="noBack">L</span>
        <span class="noBack">O</span>
     </h1> 
     
     <input id="inputBox" type="text" />

    Is anything else changing besides adding the class? Like changing the input (events) or recreating dom elements so that events get lost?

    Edited answer - Something more did seem to happen which caused the problem.

    Original fiddle (from comment below question): https://jsfiddle.net/HYUTS/y0jd2zxr/5/.

    Fixed fiddle: https://jsfiddle.net/y0jd2zxr/7/.

    This line was resetting the content of 'id1' after every keydown event: $('#id1').html(emptyArray);.

    If you remove that it works.