How can I create and style a div using JavaScript?

后端 未结 9 2260
野的像风
野的像风 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:00

    create div with id name

    var divCreator=function (id){
    newElement=document.createElement("div");
    newNode=document.body.appendChild(newElement);
    newNode.setAttribute("id",id);
    }
    

    add text to div

    var textAdder = function(id, text) {
    target = document.getElementById(id)
    target.appendChild(document.createTextNode(text));
    }
    

    test code

    divCreator("div1");
    textAdder("div1", "this is paragraph 1");
    

    output

    this is paragraph 1
    
    0 讨论(0)
  • 2020-11-27 11:03

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

    var div = document.createElement('div');
    div.innerHTML = "my <b>new</b> skill - <large>DOM maniuplation!</large>";
    // 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!

    0 讨论(0)
  • 2020-11-27 11:11

    Another thing I like to do is creating an object and then looping thru the object and setting the styles like that because it can be tedious writing every single style one by one.

    var bookStyles = {
       color: "red",
       backgroundColor: "blue",
       height: "300px",
       width: "200px"
    };
    
    let div = document.createElement("div");
    
    for (let style in bookStyles) {
     div.style[style] = bookStyles[style];
    }
    
    body.appendChild(div);
    
    0 讨论(0)
提交回复
热议问题