3

I need to add a class to an <a> that is added programmatically. When I call addClass it doesn't add it, this is I assume because the plugin hasn't finished installing all it's bits and pieces so the anchor isn't there yet.

The page is here. It's the login bar at the top. I want to add a class to the login and sign up buttons e.g.

jQuery('.bp-login a').addClass('simplemodal-login');
jQuery('.bp-signup a').addClass('simplemodal-register');

The HTML for that section is

<ul class="main-nav">
<li class="bp-login no-arrow">
    <a href="http://nicolaelvin.com/community/wp-login.php?redirect_to=http%3A%2F%2Fnicolaelvin.com%2Fcommunity">Log In
    </a>
</li>
<li class="bp-signup no-arrow">
     <a href="http://nicolaelvin.com/community/register/">Sign Up
     </a>
</li>
...</ul>
11
  • Do you install some plugin like activeX control and after that you want to add? Commented Apr 22, 2012 at 11:31
  • No its wordpress and a plugin loads, and after that I want to add, but its a similar thing Commented Apr 22, 2012 at 11:32
  • I know about .on() but I think this only works with events Commented Apr 22, 2012 at 11:33
  • The .on() method attaches event handlers to the currently selected set of elements but you have to check if document controls are ready to use and that you get in ready method Commented Apr 22, 2012 at 11:38
  • Hi Nix. Give an example of the loaded html and Ill explain Commented Apr 22, 2012 at 11:44

2 Answers 2

2

Try:

jQuery(function() {

    var modal_check = setInterval(function(){

        if(jQuery('.simplemodal-login').length > 1){
            clearInterval(modal_check);
            jQuery('.bp-login a').addClass('simplemodal-login');
            jQuery('.bp-signup a').addClass('simplemodal-register');
        }

    },100);

});​

This waits until the dom is ready then checks every 10th of a second to see if the modal plugin has loaded. Once the plugin has loaded it stops the interval and adds the class.

Sign up to request clarification or add additional context in comments.

3 Comments

I suppose that plugin should have some callback for this action.
Isn't there any jQuery event that could be used instead of setInterval?
@PetrPeller There could be a onload callback for the plugin mentioned but without knowing that an interval is the only other option.
-1

You should wait until DOM is ready.

$(function () {
  $(element).addClass('hello');
});

1 Comment

that doesn't work because the element hasn't been added as normal, it's done with jquery so I think as far as jQuery knows, it's done, when it's isn't. If that makes sense...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.