简体   繁体   中英

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.

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);

尝试document.createElement。

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

Try

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

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');

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM