In the past, Drupal.AjaxCommands.prototype.insert()
always wraps the returned HTML in a div. This has proven to be problematic, creating multiple wrapping divs, making styling challenging.
Ajax responses will still be wrapped with a div when the ajax response tries to insert multiple root elements with a ajax effect due to BC reasons. This will be removed before Drupal 9.0.0 See more about it in the #736066-284: ajax.js insert command sometimes wraps content in a div, potentially producing invalid HTML and other bugs.
Instructions to update your code
Before (deprecated, markup will change in Drupal 9.0.0):
// Controller for AJAX response
public function myAjaxResponse() {
return [
'content' => [
'#template' => '<p>item 1</p><p>item 2</p>',
],
'effect' => 'fade',
];
}
// Result on the client side (wrapping div added by ajax system before Drupal 9.0.0):
<div><p>item 1</p><p>item 2</p></div>
After:
// Controller for AJAX response
public function myAjaxResponse() {
return [
'content' => [
'#template' => '<div class="my-best-wrapper"><p>item 1</p><p>item 2</p></div>',
],
'effect' => 'fade',
];
}
// Result on the client side (markup as expected):
<div class="my-best-wrapper"><p>item 1</p><p>item 2</p></div>
Removing the wrapper completely
If you want to completely remove the wrapper, you can use next code in your JavaScript:
(function(Drupal) {
Drupal.theme.ajaxWrapperMultipleRootElements = function (elements) {
return elements;
};
}(Drupal));
However, in this case you will have to ensure that all ajax responses already contain a single root level element.
If you need to completely restore the previous behavior, you can use next code, but if there is something we should look into, please report a bug:
(function($, Drupal){
Drupal.theme.ajaxWrapperNewContent = function ($newContent, ajax, response) {
if ($newContent.length > 1) {
$newContent = $('<div></div>').append($newContent);
}
return $newContent;
};
}(jQuery, Drupal));
See more about ajaxWrapperMultipleRootElements
and ajaxWrapperNewContent
in the /core/misc/ajax.es6.js
.