JavaScriptを使用してdivを作成してスタイルを設定するにはどうすればよいですか?


回答:


273

var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";

document.getElementById("main").appendChild(div);
<body>
<div id="main"></div>
</body>

var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";

document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);

の代わりに親参照を使用しdocument.bodyます。


私はこれが古いことを知っていますが、クラスと関連するCSSを追加する方がよりモダンなアプローチになるでしょうが、それは別の問題です。
マークシュルタイス

63

あなたがそれをやっている方法に依存します。純粋な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);

jqueryを使用して同じことを行うのは恥ずかしいほど簡単です。

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

乾杯!


4
jQueryの方が簡単だとは思いませんが、ほとんどが短いだけです。ただし、クラスにsetAttributeを使用する代わりに、div.className = 'myclass';を使用します。
Daan Wilmer、2011

4
重いJavaScript UIの開発を始めると、jQueryはとても簡単になります。最初からプログラミングの機能モデルを採用しているため、コードの外観と動作も機能します。
適例

3
jQueryを「機能的」と呼ぶことは大きなストレッチです。機能モデルをどのように定義し、jQueryがそれをどのように取り入れていると思いますか?

アプリケーションに10行ある場合、jqueryは最適です。深刻なアプリケーションを作成する場合は、地獄へようこそ。簡潔さは自動的に適切なプログラミングではありません/
Hal50000

ここでのjQueryの部分には、a divが追加されていないため、質問に回答していません
Mark Schultheiss

10

ここで他の答えは機能しますが、コンテンツを含むdivを要求したことに気づきました。だからここに追加のコンテンツを含む私のバージョンがあります。下部のJSFiddleリンク。

JavaScript (コメント付き)

// 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:

<body>
  <h1>Title</h1>
  <p>This is a paragraph. Well, kind of.</p>
</body>

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

注:ラタールトマルから借りたCSS行

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


9

このソリューションはjqueryライブラリを使用します

$('#elementId').append("<div class='classname'>content</div>");

14
おかしなJavascript。
TheCarver 2016

5

これが私が使用する1つの解決策です:

var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';

属性や属性値を変数に基づくようにしたい場合:

var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';

次に、本文に追加します。

document.getElementsByTagName("body").innerHTML = div;

やさしい。


HTMLページに何を書けばよいですか?
Nahiduzzaman Rose氏2017

1
[0]使用するときに指定する必要がありますgetElementsByTagName()。(編集するには短すぎます)
HKJeffer

2

このように作成できます

board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"

document.getElementById("main").appendChild(board);

完全な実行可能なスニペット:

var board;
board= document.createElement("div");
board.id = "mainBoard";
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"
    
document.getElementById("main").appendChild(board);
<body>
<div id="main"></div>
</body>


2

ID名でdivを作成する

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

divにテキストを追加する

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

テストコード

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

出力

this is paragraph 1

1

私がやりたいもう1つのことは、オブジェクトを作成してから、オブジェクト全体をループし、そのようにスタイルを設定することです。

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);
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.