user7461846
user7461846

Reputation:

jquery selector after addClass

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>

Upvotes: 0

Views: 62

Answers (2)

Morteza Fathnia
Morteza Fathnia

Reputation: 435

$(document).ready(function(){
console.log($('.parent'))
$('div.parent').clone().appendTo("body").addClass('lorem');

$('.lorem').insertBefore('.parent');
})

Upvotes: -2

Manoz
Manoz

Reputation: 6597

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

Upvotes: 3

Related Questions