adding and manipulating a div via jquery, without using any html like code

I have an odd question, I know, but is there a way to adding a div element to a specific element without write any html code in the javascript function?

what I mean is:

I normally use this:

  $(".divclass").append("<div>Test</div>");

but this is easy to "read", i would like something like:

  $(".divcalss").append(newDiv.text( "Test");

I would like to have NO HTML inside the javascript, i can achieve it when I manipulate css, or attributes, or many other thigs... but is there a way to this to add a div?

thanks in advance.

Upvotes: 0

Views: 100

Answers (5)

ashley
ashley

Reputation: 2767

Also, if you would like something that is reusable:

$.fn.appendNew = function() {
    var el = document.createElement('div');
    var $el = $(el); 
    this.each(function() {
        $(this).append(el);
    });
    return $el;
}

$('p').appendNew().text('world').css('color', 'red');

http://jsfiddle.net/LKZTC/1/

Upvotes: 1

Stuart Kershaw
Stuart Kershaw

Reputation: 17681

You can create a new DOM element with something like:

var div = document.createElement('div');

This then becomes a document fragment until it's inserted into the document (or your specified element) with some JS:

var myElement = document.getElementById('myElement');
myElement.appendChild(div);

If you'd rather us jQuery for the insertion:

$('#myElement').append(div);

Upvotes: 3

Alex Vogt
Alex Vogt

Reputation: 165

You can create an HTML element by using document.createElement().

Try this:

function addElement() {
    var newdiv = document.createElement('div');
    newdiv.innerHTML = 'Test';

    $(".divclass").append(newdiv);
}

You can add attributes with the following method:

newdiv.setAttribute('id', 'newdiv');

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388416

Try

var newDiv = document.createElement('div'); 
$(newDiv).text('asd').appendTo('.divclass')

Upvotes: 1

ED-209
ED-209

Reputation: 4746

Try document.createElement.

var myDiv = document.createElement('div'); 

Upvotes: 1

Related Questions