only-child

」は、親の唯一の子であるすべての要素を選択するために使用されます。

  1. $( ‘:only-child’) – 子要素のすべての要素を選択します.

その親。

  1. $( ‘li:only-child’) – <li>と一致するすべての要素を選択します.

その親の子のみ。

jQueryの例

この例では、ボタンをクリックすると、親の唯一の子であるため、

<li> DEF#1 </li>

だけが一致し、背景色を動的に変更します。

<html>
<head>
<title>jQuery only child example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>

<body>

<h1>jQuery only child example</h1>

<ul>
    <li>ABC #1</li>
    <li>ABC #2</li>
    <li>ABC #3</li>
    <li>ABC #4</li>
    <li>ABC #5</li>
</ul>

<ul>
    <li>DEF #1</li>
</ul>

<ul>
    <li>GHI #1</li>
    <li>GHI #2</li>
</ul>

<button>li:only-child</button>

<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("li").css("background", "white");
      $(str).css("background", "coral");
    });
</script>

</body>
</html>

リンク://wp-content/uploads/jQuery/jQuery-only-child.html[デモを試してください]