简体   繁体   中英

jQuery - Select an element by ID not working

I'm trying to select an element and then add / remove a class. I have achieved this plenty of times with other elements, however for this one it doesn't want to work.

My html is as follows:

<div>
 <a class="login-headerText" id="hypLogin" style="padding-right:5px; float:left" >Login</a>
 <h4 class="login-headerText" style="font-weight:bold; padding-right:5px; float:left">/</h4>
 <a class="login-headerText"  id="hypCreateAccount">Create Account</a>
</div>   

The div is wrapped inside another div. (id=modal)

I want to select "hypLogin" then add a class to it on click. It works if i do this in the onClick event, however it wont work in a seperate script. (The script is referenced and works as it is used for other elements)

This is my jQuery

$('#hypLogin').click(function () {
    $(this).removeClass('login-headerText').addClass('login-headerText-Unselected');
});

Tried debugging it and it's not getting hit at all.

Probably something really simple.

Couple of things:

  1. you must do it on:

     $( document ).ready(function() { }); 
  2. Does these elements printed dynamically?

  3. try to use:

     $('#hypLogin').on('click', function () { }); 
  4. try to put your code on modal open event.

Here is working fiddle

try this:

$(document).ready(function () {
    $('#hypLogin').click(function () {

        $(this).removeClass('login-headerText').addClass('login-headerText-Unselected');
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM