1
1

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】入れ子になったulタグとその親のliタグのclassnameを取得する

Posted at
001.html

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>入れ子になったulタグとその親のliタグのclassnameを取得する</title>
<style type="text/css">
</style>
</head>
<body>

<h3>JavaScript</h3>

<ul  id="menu">
  <li>配列</li>
  <li class="parent_1">関数
    <ul class="child_1">
      <li>Functionオブジェクト</li>
      <li class="parent_2">関数の呼び出し
       <ul class="child_2">
           <li><a href="#">メソッド呼び出しパターン</a></li>
           <li><a href="#">関数呼び出しパターン</a></li>
           <li><a href="#">コンストラクタ呼び出しーンパターン</a></li>
           <li><a href="#">apply呼び出しパターン</a></li>
       </ul>
   </li>
    </ul>
  </li>
</ul>

<script type="text/javascript">

window.onload=function(){

  var element = document.getElementById("menu").getElementsByTagName("ul");

  for(i=0;i<element.length;i+=1){
     console.log("element[" + i + "].className="+element[i].className);
     console.log("element[" + i + "].parentNode.className="+element[i].parentNode.className);
  }

}

/*
"element[0].className=child_1"
"element[0].parentNode.className=parent_1"
"element[1].className=child_2"
"element[1].parentNode.className=parent_2"
*/

</script>
</body>
</html>

解説

jQuery等のライブラリの使用せずに、入れ子になったulタグとその親のliタグのclassnameを取得する。

var element = document.getElementById("menu").getElementsByTagName("ul");
element.length//2

javascriptを勉強して長いが、document.getElementById().getElementsByTagName()って初めて書いた。
element.lengthって3じゃなく2であることに驚いた。

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?