ReynierPM ReynierPM - 1 month ago 10
Javascript Question

How to turn dynamic DOM element into Select2?

I have the following HTML code:

<input type="text" id="condition_value_1">
<span class="click_me">Click Me</span>


I am replacing the
#condition_value_1
element with a SELECT type as follow and trying to turn the recently SELECT into a Select2:

$(function() {
$('.click_me').click(function(ev) {
var condition_value_1 = $('#condition_value_1');
var select_html = '<select name="condition_value_1" id="condition_value_1"></select>';
condition_value_1.replaceWith(select_html);

$('body').on('DOMNodeInserted', '#condition_value_1', function() {
$(this).select2({
placeholder: 'Start typing ...',
tags: true
});
});
});
});


But is not working since the element keep as a normal HTML Select type and doesn't turn into a Select2. Here is a Fiddle for you to play with. I am using jQuery 1.12.4 and Select 4.0.3.

How do I turn a dynamic element into a Select2 element? Any help?

Answer

Seems to work for me if not using DOMNodeInserted event binding.

It's fair to assume the element has been added to the DOM when the replaceWith() method is called.

JS Fiddle updated

$(function() {
  $('.click_me').click(function(ev) {
    var condition_value_1 = $('#condition_value_1');
    var select_html = '<select name="condition_value_1" id="condition_value_1"></select>';
    condition_value_1.replaceWith(select_html);

    $('#condition_value_1').select2({
        placeholder: 'Start typing ...',
        tags: true
      });
  });
});