How can I create and style a div using JavaScript?

后端 未结 9 2258
野的像风
野的像风 2020-11-27 10:27

How can I use JavaScript to create and style (and append to the page) a div, with content? I know it\'s possible, but how?

9条回答
  •  有刺的猬
    2020-11-27 11:03

    Depends on how you're doing it. Pure javascript:

    var div = document.createElement('div');
    div.innerHTML = "my new skill - DOM maniuplation!";
    // set style
    div.style.color = 'red';
    // better to use CSS though - just set class
    div.setAttribute('class', 'myclass'); // and make sure myclass has some styles in css
    document.body.appendChild(div);
    

    Doing the same using jquery is embarrassingly easy:

    $('body')
    .append('my DOM manupulation skills dont seem like a big deal when using jquery')
    .css('color', 'red').addClass('myclass');
    

    Cheers!

提交回复
热议问题