doniyor
doniyor

Reputation: 37904

insertbefore and find the css class - js not working

I am adding some element with content before this div

<div id="before_this">
  blablabla
</div>

my js:

$('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this').find('.comment');

but the class comment properties wont be applied to new added element.

how can I achieve this in jquery?

Upvotes: 1

Views: 524

Answers (3)

VisioN
VisioN

Reputation: 145408

How is that? It is applied, since you create a new element <p> with class .comment. However .find() won't work, because there are no descendants of the <p>, which have class .comment.

If you need to work with the inserted element, go on and use chaining:

$("<p class='comment'>...</p>").insertBefore("#before_this").css("color", "red");

Upvotes: 2

Derek Henderson
Derek Henderson

Reputation: 9706

The .find() at the end looks for an element inside the selected element. Since the element you are looking for is the selected element, this will never work. (In other words, there are no descendants of p.comment that have class "comment.")

If what you want to do is select the element you've just created, it's already selected.

var selectedElement = $('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this');
// selectedElement === $('p.comment');

If you want the class name, use the following instead:

$('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this').attr('class');

But of course that makes no sense since you already know that the class of the element you created and gave a class of "comment" to will be "comment"!

Upvotes: 1

elclanrs
elclanrs

Reputation: 94121

insertBefore returns the collection on which it was called. This collection in your example is already p.comment.

Try this in console and you'll see the p.comment jQuery object:

var $p = $('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this');

console.log($p); // p.comment jQ object

Upvotes: 2

Related Questions