Ajax in textfield adding extra div in markup I have created a form using a custom module. I am working on ajax functionality and updating markup when user enter text in textfield of the form.

Creating form in module

/**
 * Implements hook_form().
 */            

  $form['name'] = array(
    '#type' =&gt; 'textfield',
    '#description' =&gt; 'Enter your name',
    '#title' =&gt; 'Name',
    '#size' =&gt; 50,
    '#ajax' =&gt; array(
        'callback' =&gt; 'custom_print_ajax_name_callback',
        'wrapper' =&gt; 'custom-print-name',
        'method' =&gt; 'replace',
  ),
  );   

  $form['name_msg'] = array(
    '#type' =&gt; 'item',
    '#markup' =&gt; (!empty($form_state['input']['name']) ? $form_state['input']['name'] : ''),
    '#prefix' =&gt; '&lt;div id="custom-print-name"&gt;',
    '#suffix' =&gt; '&lt;/div&gt;',

  );


Ajax submit callback:

/**
 * Ajax callback
 */
function custom_print_ajax_name_callback($form, &amp;$form_state) {

  return $form['name_msg'];
}


Everything is working correctly except that when I checked HTML of the page, an extra div is added in HTML of markup after updating ajax as shown in below image.

I do not have any idea why is this extra div rendering with markup.

Thanks in advance.
I have checked ajax.js in Drupal site and I have found that extra div is added as ajax wraps new content inside an empty div after a successful ajax request.

Comment Mentioned in ajax.js:


  We don't know what response.data contains: it might be a string of
  text without HTML, so don't rely on jQuery correctly iterpreting
  $(response.data) as new HTML rather than a CSS selector. Also, if
  response.data contains top-level text nodes, they get lost with either
  $(response.data) or $('&lt;div&gt;&lt;/div&gt;').replaceWith(response.data).


Code:

var new_content_wrapped = $('&lt;div&gt;&lt;/div&gt;').html(response.data);
var new_content = new_content_wrapped.contents();


Check this also.