Why this doesn't work:
$('.parent').clone().addClass('lorem');
$('.lorem').insertBefore('.parent');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>lorem</div>
答案 0 :(得分:3)
You are targeting element which is not in DOM yet.
You can try
var cloneElement = $('.parent').clone().addClass('lorem');
cloneElement.insertBefore('.parent');
You might need to insert cloned element in the DOM in order to select it.
Now if you log the .lorem
element, You will be able to find it.
You can verify -
console.log($('.lorem').length) //returns 1 element
答案 1 :(得分:-1)
$(document).ready(function(){
console.log($('.parent'))
$('div.parent').clone().appendTo("body").addClass('lorem');
$('.lorem').insertBefore('.parent');
})