[解決済み] how to add new <li> to <ul> onclick with javascript
2022-12-09 04:20:36
Question
How do I add a list element to an existing ul using a function from an onclick? I need it to add to this type of list ...
<ul id="list">
<li id="element1">One</li>
<li id="element2">Two</li>
<li id="element3">Three</li>
</ul>
... another list item with the id "element4" and text "Four" under that. I tried this function but it doesn't work...
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
}
I don't know JQuery so Javascript only please. Thank you!!
How to solved?
You have not appended your
li
as a child to your
ul
element
Try this
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
ul.appendChild(li);
}
idを設定する必要がある場合、以下のようにします。
li.setAttribute("id", "element4");
これは、この関数を
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
li.setAttribute("id", "element4"); // added line
ul.appendChild(li);
alert(li.id);
}
関連
-
[解決済み] 配列から特定の項目を削除するにはどうすればよいですか?
-
[解決済み] JavaScriptで "use strict "は何をするのか、その根拠は?
-
[解決済み] JavaScriptで文字列が部分文字列を含むかどうかを確認する方法は?
-
[解決済み] あるJavaScriptファイルを他のJavaScriptファイルにインクルードするにはどうすればよいですか?
-
[解決済み] JavaScriptでメールアドレスを検証するのに最適な方法は何ですか?
-
[解決済み] JavaScriptでタイムスタンプを取得する方法は?
-
[解決済み] JavaScriptで要素のクラスを変更するにはどうすればよいですか?
-
[解決済み】JavaScriptで文字列の出現箇所をすべて置換する方法
-
[解決済み】オブジェクトからプロパティを削除する(JavaScript)
-
[解決済み] Javascript / jQueryでAndroid端末を検出する。
最新
-
nginxです。[emerg] 0.0.0.0:80 への bind() に失敗しました (98: アドレスは既に使用中です)
-
htmlページでギリシャ文字を使うには
-
ピュアhtml+cssでの要素読み込み効果
-
純粋なhtml + cssで五輪を実現するサンプルコード
-
ナビゲーションバー・ドロップダウンメニューのHTML+CSSサンプルコード
-
タイピング効果を実現するピュアhtml+css
-
htmlの選択ボックスのプレースホルダー作成に関する質問
-
html css3 伸縮しない 画像表示効果
-
トップナビゲーションバーメニュー作成用HTML+CSS
-
html+css 実装 サイバーパンク風ボタン
おすすめ
-
[解決済み] URL/アドレスバーからJavascriptの関数を呼び出す
-
[解決済み] bootstrap のポップオーバーがすべての要素の上に表示されない
-
[解決済み] Javascript / jQueryでAndroid端末を検出する。
-
[解決済み] JavaScript のオブジェクトの配列を比較し、最小値/最大値を取得する
-
[解決済み] $.ajax実行中にローディングイメージを表示する
-
[解決済み] イテレータでmap()を使用する
-
[解決済み] JavaScriptとLuaの微妙な違い [終了しました]
-
[解決済み] JavaScriptのArray.sort()メソッドでシャッフルするのは正しいのか?
-
[解決済み] V8 Javascript エンジンのスタンドアロン実行
-
[解決済み] 変異を伴わないオブジェクトからの値の削除