Rouge
Rouge

Reputation: 4239

How to simplify my create element code?

I am trying to create 2 elemets, 1 with id and 1 without. I have the following code and want to know how to simplify it. Any helps? Thanks a lot.

 var element = $('<div/>').attr({'id': tool}).addClass('s-Tool')             
                .append(
                  $('<div/>').css({'padding': '0.5em 1em'}).html(text)
               );

//only different is attr id

 var elementClass = $('<div/>').addClass('s-Tool')             
                .append(
                  $('<div/>').css({'padding': '0.5em 1em'}).html(text) 
               );

Upvotes: 0

Views: 72

Answers (2)

adeneo
adeneo

Reputation: 318222

var elementClass = $('<div />', {'class': 's-Tool'})
                   .append($('<div/>').css('padding', '0.5em 1em').html(text)),
    element = elementClass.clone(true).attr('id', tool);

Upvotes: 2

jfriend00
jfriend00

Reputation: 707446

You can just use the actual HTML:

var element = $('<div id="tool" class="s-Tool"><div style="padding: 0.5em 1em;">' + text + '</div></div>')

To do this with a different id, you can make it a function:

function makeMyElement(id, text) {
    var element = $('<div id="' + id + '" class="s-Tool"><div style="padding: 0.5em 1em;">' + text + '</div></div>')
    return(element);
}

Upvotes: 0

Related Questions