user1477955
user1477955

Reputation: 1670

How to append element and get its selector

I want to append a div and afterwards to be able to select it. Can my code be optimized?

JS:

$someEle.append("<div><span>5</span><span>€</span></div>");
var $newELE = $someEle.find('div');

Upvotes: 1

Views: 23

Answers (1)

adeneo
adeneo

Reputation: 318182

Create the elements first, that way they are easily accessible both before and after you append them

var div   = $('<div />'),
    span1 = $('<span />', {text : '5'}),
    span2 = $('<span />', {text : '€'});

$someEle.append( div.append( span1, span2 ) );

div.css('color', 'red'); // use element

Upvotes: 2

Related Questions