简体   繁体   中英

Adding class to next element using jquery

I am having html like this:

<form>
    <div class="row">
        <input type="radio" class="radio">
        <label>Text</label>
        <input type="radio" class="radio">
        <label>Type</label>
    </div>
</form>

Now I need to apply a class to each label immediate after each <input type="radio"> .

I am using jquery like this:

if($('input').hasClass('radio')){
    $(this).next().addClass('radio-url');
}

I am trying to add class 'radio-url' to each <label> immediately after radio tag. What mistake have I did in this?

You can use .siblings()

$('input[type="radio"]').siblings('label').addClass('radio-url');

DEMO

Or

$('input[type="radio"]').next('label').addClass('radio-url');

DEMO2

Try:

$(':radio').next().addClass('radio-url');

jsFiddle example (I threw a text input in there so you can see that it works on only radio inputs)

您可以使用next()函数

 $("input:radio").next('label').addClass("radio-url");`

This answer doesn't directly answer your question!

I believe that your label should have the for attribute so that the label is associated with the radio button. This allows the user:

  1. To check the radio button by clicking the label!
  2. If the input type is text, clicking the label focuses the text input
  3. For accessibility reasons

HTML

<div class="row">
    <input type="radio" class="radio" id="text"></input>
    <label for="text">Text</label>
    <input type="radio" class="radio" id="type"></input>
    <label for="type">Type</label>
</div>

JQuery

Search the label using the radio element's ID.

$('input[type="radio"]').each(function(){
    var radioId = $(this).attr("id");
    $("label[for='" + radioId + "']").addClass('radio-url');
});

Fiddle: http://jsfiddle.net/78zAB/

You need to loop through all radio buttons:

$('input[type="radio"]').each(function(){
    $(this).next().addClass('radio-url');
});

Or

$("input[type='radio'] + label").addClass('radio-url')

Fiddle Example

Example 2

DEMO

$('input.radio').each(function () {
    $(this).next().addClass('radio-url');
})

Use CSS element+element selector:

$('input:radio + label').addClass('theClass')

http://jsfiddle.net/ttnUU/

Works optimal

$('input[type=radio]').next('label').addClass('radio-url');

http://jsfiddle.net/q76FJ/

Posting this as an answer as all of the others are using the incorrect selector, or don't specify the label in next() :

$('input.radio').next('label').addClass('radio-url');

.. which will add the class radio-url to all label elements which come immediately after an input with the class radio

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