如何在jQuery中获取元素的同级元素

时间:2020-02-23 14:46:01  来源:igfitidea点击:

在本文中,我们将讨论如何在jQuery中获取HTML元素的同级元素。
jQuery API提供了" siblings()"方法来实现此功能。

jQuery siblings()

siblings()方法用于返回所选HTML元素的所有同级对象。
与jQuerynext()prev()方法不同,此方法沿所选元素的同级对象前后移动。
当您要对一组元素执行类似任务时,此方法非常方便。

这是使用同级方法的一般语法:

  • selector.siblings([filter])

filter是传递给该方法以缩小遍历范围的可选参数。

jQuery siblings()示例

以下示例演示了jQuery siblings()的用法。

<!doctype html>
<html>
<head>
<title>jQuery Traversing siblings</title>
<style>
  span{
     color: blue;
     margin: 30px;
     font-size: 16px;
     padding: 5px;
     font-weight: bolder;
     border: 1px solid lightgrey;
   }

  .highlight{
     background: yellow;
   }

  div{ 
    display: block;
    border: 3px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 25px;
    width:350px;
   }
</style>

<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
</head>
<body>
<div>
 Bheem
<span class="highlight"> Arjun
 Nakul
</div>
<div>
 Mark
<span class="highlight"> Tom 
 Steve
</div>
<div>
 Sachin
 Saurav
 Zaheer 
</div>
<script>
 $( ".highlight" ).siblings()
.css( "color", "red" );
</script>
</body>
</html>

在此示例中,您可以看到三个div元素,每个div具有三个span元素。
在第一个和第二个" div"元素中,第二个跨度具有CSS样式类" highlight"。
siblings()方法返回具有class =" highlight"的所选元素的所有同级并将同级颜色更改为红色。

在第一个div中,Bheem和Nakul是Arjun的兄弟姐妹,在第二个div中,Mark和Steve是Tom的兄弟姐妹。