5

I have a problem, and try it to solve two more days. Try do it like this:

$.when( $(document).ready ).then(function func_fold () {
  $( "#collapsible_sidebar" ).addClass('folded');    
})

And like this:

$(document).ready(function func_fold () {
  $( "#collapsible_sidebar" ).addClass('folded');    
})

And like this too:

$(document).ready(function() {
  $( "#collapsible_sidebar" ).addClass('folded');    
})

Try .hide() to see work selector at all, and it doesn't work too. But when I open DOM, I can see this element and this ID.

Warning! I think it important, this div is added to DOM by AJAX.

HTML element:

<div id="collapsible_sidebar"><?php dynamic_sidebar( 'sidebar-1' ); ?></div>
  • Can you explain what's not working? The last one you have there works. – jerrylow Mar 08 '19 at 17:17
  • 1
    Add relevant HTML and convert it into a snippet. Then we can **see** what you are trying to say. – PM 77-1 Mar 08 '19 at 17:17
  • Yeah the element doesn't exist when document.ready triggers, so you'll need to add this class once the element *does* exist. – James Mar 08 '19 at 17:17
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Taplar Mar 08 '19 at 17:28

1 Answers1

12

If it's being added to the DOM by AJAX, that means it's being added sometime after $(document).ready(). AJAX stands for "Asynchronous Javascript And XML", asynchronous meaning that it will execute on its own time when the server can get to it. If you want to execute that class being added, you need to put $("#collapsible_sidebar").addClass('folded'); into the success function in your AJAX call.

$.ajax({
    //other parameters
    success: function () {
        $("#collapsible_sidebar").addClass('folded');
    }
});
el toro
  • 532
  • 4
  • 11