How can I create and style a div using JavaScript?

后端 未结 9 2309
野的像风
野的像风 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 10:54

    While other answers here work, I notice you asked for a div with content. So here's my version with extra content. JSFiddle link at the bottom.

    JavaScript (with comments):

    // Creating a div element
    var divElement = document.createElement("Div");
    divElement.id = "divID";
    
    // Styling it
    divElement.style.textAlign = "center";
    divElement.style.fontWeight = "bold";
    divElement.style.fontSize = "smaller";
    divElement.style.paddingTop = "15px";
    
    // Adding a paragraph to it
    var paragraph = document.createElement("P");
    var text = document.createTextNode("Another paragraph, yay! This one will be styled different from the rest since we styled the DIV we specifically created.");
    paragraph.appendChild(text);
    divElement.appendChild(paragraph);
    
    // Adding a button, cause why not!
    var button = document.createElement("Button");
    var textForButton = document.createTextNode("Release the alert");
    button.appendChild(textForButton);
    button.addEventListener("click", function(){
        alert("Hi!");
    });
    divElement.appendChild(button);
    
    // Appending the div element to body
    document.getElementsByTagName("body")[0].appendChild(divElement);
    

    HTML:

    
      

    Title

    This is a paragraph. Well, kind of.

    CSS:

    h1 { color: #333333; font-family: 'Bitter', serif; font-size: 50px; font-weight: normal; line-height: 54px; margin: 0 0 54px; }
    
    p { color: #333333; font-family: Georgia, serif; font-size: 18px; line-height: 28px; margin: 0 0 28px; }
    

    Note: CSS lines borrowed from Ratal Tomal

    JSFiddle: https://jsfiddle.net/Rani_Kheir/erL7aowz/

提交回复
热议问题