daman daman - 14 hours ago 2
jQuery Question

Insert new span element after input element if it does not already exist

This is how my html code looks like:

<label><span>1</span><input type="radio" value="1" name="choice">
<span>Poor</span></label>

<label><span>2</span><input type="radio" value="2" name="choice"></label>

<label><span>3</span><input type="radio" value="3" name="choice"></label>

<label><span>4</span><input type="radio" value="4" name="choice"></label>

<label><span>5</span><input type="radio" value="5" name="choice">
<span>Great</span></label>


The second, third and fourth label blocks do not have a span element after input element. If in such a list, there is no span after input element, I need to insert an empty span tag.

<span></span>


So the output looks like:

<label><span>1</span><input type="radio" value="1" name="choice">
<span>Poor</span></label>

<label><span>2</span><input type="radio" value="2" name="choice"><span>
</span></label>

<label><span>3</span><input type="radio" value="3" name="choice"><span>
</span></label>

<label><span>4</span><input type="radio" value="4" name="choice"><span>
</span></label>

<label><span>5</span><input type="radio" value="5" name="choice">
<span>Great</span></label>


I am new to jQuery and this is what I am trying so far:

$('input').each(function() {
if($(this).closest('span').length<1) {
$('input').after("<span></span>");
}
});


But this inserts several empty spans in each label block. Any help is appreciated.

Answer

You have to use $(this) instead of $('input') to target the current element in the loop:

$('input').each(function(i) {
  if ($(this).next('span').length < 1) {
    $(this).after("<span style='color: #f00;'>" + i + "</span>");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><span>1</span><input type="radio" value="1" name="choice">
<span>Poor</span></label>

<label><span>2</span><input type="radio" value="2" name="choice"></label>

<label><span>3</span><input type="radio" value="3" name="choice"></label>

<label><span>4</span><input type="radio" value="4" name="choice"></label>

<label><span>5</span><input type="radio" value="5" name="choice">
<span>Great</span></label>

Also, you can use next() method to check if there is an span next to the input. I used next because closest() looks for the parent elements only, so it will not work for what you are trying to do.