JQuery: Changing CSS on an element loaded with ajax?

I need to reposition the element that I am loading with ajax . I want to use .css() to change it, but jQuery cannot find the element because it is not recognized. How to make jQuery "recognize" an element?

I read about live() and delegate() , but I can't get any of them to work the way I want them to. I would really appreciate help!

+6
source share
3 answers

Make a css change to the complete or success function of the ajax call. Assuming you are using load :

 $('#el').load( url, data, function(){ $('#selector').css('position', 'absolute'); } ); 

Alternatively (and easier to give as an example), register the ajaxComplete event

 $(document).ajaxComplete(function(){ if($('#elementID').length != 0) { $('#elementID').css('position', 'absolute'); } }); 

This runs every time an ajax request is made, checks if #elementID exists, and if applicable to css.

+17
source

If you need markup in the js variable, you can do this as shown below.

 $(markup).find("requiredElement").css({ set the properties here }); 
+1
source

If you want to edit CSS, you first need to put it in the DOM and then manipulate it.

Example:

 $.ajax({ ... success:function(data){ $('<div/>').appendTo('body').html(data).css('border','3px solid red'); } }); 
0
source

Source: https://habr.com/ru/post/893824/


All Articles