Alexander Virko
Alexander Virko

Reputation: 37

Why does replaceWith cancels calls to its variable?

I'm trying to clone dom elements and change their tags. But after I replace the main element I cannot change its children nor apply some click events.

I commented line after which it stops working. Thanks for help!

http://codepen.io/sanns/pen/eJvzBN?editors=101

var selectDom = $('select');
selectDom.each(function() {
  var clone = $(this).clone().insertAfter(this);

  //take classes from clone
  var classesStr = clone.attr('class');

  clone = clone.replaceWith(function(index, oldHTML) {
    return $('<div class="custom-select ' + classesStr + '">').html(oldHTML);
  });

//why does not work?
  clone.find('option').replaceWith(function(index, oldHTML) {
    return $('<li>').html(oldHTML);
  });

  clone.wrapInner('<ul class="scrollbox"></ul>').prepend('<span class="shower"> Выберитеtttttttttteeeee тратататататат</span>');



  //BEHAVIOR SELECT
  clone.on('click', function() {
    alert('asdf');
  });

});

Upvotes: 0

Views: 38

Answers (1)

Bhavin Solanki
Bhavin Solanki

Reputation: 4818

Actually .replaceWith() returns the original jQuery object, not the replacement with something.

You can find more details : http://api.jquery.com/replacewith/

Here is the small example of it:

$( "button" ).click(function() {
  $( this ).replaceWith( "<div>" + $( this ).text() + "</div>" );
});
button {
    display: block;
    margin: 3px;
    color: red;
    width: 200px;
  }
  div {
    color: red;
    border: 2px solid blue;
    width: 200px;
    margin: 3px;
    text-align: center;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>First</button>
<button>Second</button>
<button>Third</button>

Upvotes: 1

Related Questions