简体   繁体   中英

to add class to neighbour html element jquery

I want to add the class fas fa-exclamation-circle to span tag

 $("#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.

.siblings() looks at their siblings.

  1. Use .next() to target the next element

 $("#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'.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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