1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでfor文を使わずに、<ul>の全ての子要素を消す方法

Last updated at Posted at 2019-06-13

やりたいこと

JavasScriptリストに子要素があったら、その子要素を全て消したい!

index.html
<ul id="abc_list">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

やりたくないこと

要素分ループさせて、子要素をひとつずつ消していく

ちょこっと調べてみて一番回答の多かったのはこの方法でした。
・・・やりたくなかった。だっていついかなるときだって全部消すんだもん!
ひとつひとつのデータなんて意識せずにコード書きたい!!

index.js
var ul = document.getElementById("abc_list")
var ulLen = ul.children.length

for (var i = 0; i < ulLen; i++) {
  ul.children[0].remove()
}

お気に入りの逸品

index.js
document.getElementById("abc_list").innerHTML = ""

感想

なんだ、簡単なことだったや!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?