简体   繁体   English

将类添加到邻居html元素jquery

[英]to add class to neighbour html element jquery

I want to add the class fas fa-exclamation-circle to span tag 我想将fas fa-exclamation-circle类添加到span标签

 $("#gpsno").closest('span').addClass('fas fa-exclamation-circle'); 
 <input id="gpsno" class="form-control " type="text"> <span class="form-control-feedback"></span> 

You can do this: 你可以这样做:

$("#gpsno").siblings('span').addClass('fas fa-exclamation-circle');

.closest() looks at all the elements' ancestors. .closest()查看所有元素的祖先。

.siblings() looks at their siblings. .siblings()查看其兄弟姐妹。

  1. Use .next() to target the next element 使用.next()定位下一个元素

 $("#gpsno").next('span').addClass('fas fa-exclamation-circle'); 
 .fas { color: red } .fa-exclamation-circle { font-size: 19px } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="gpsno" class="form-control " type="text"> <span class="form-control-feedback">123</span> <span class="">123</span> 

To add a class to the next neighboring html element (in this case the span), you should replace 'closest' with 'next'. 要将类添加到下一个相邻的html元素(在本例中为span),应将“ closest”替换为“ next”。

From the documentation, we can see that 'closest' looks at the ancestor elements of the set it was called on to find a match to the selector while 'next' simply retrieves the next subsequent (sibling) element in the document matching the selector. 从文档中,我们可以看到“最接近”查看调用它的集合的祖先元素以找到与选择器的匹配项,而“下一个”仅检索文档中与选择器匹配的下一个后续(同级)元素。

直接在跨度类选择器上应用添加类

$('.form-control-feedback').addClass('fas fa-exclamation-circle');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM