Skip to content
Advertisement

How to add a class to a span element which is part of an existing tag with jQuery

How can I add a class to a span element for only these spans which are part of li tags with class='error' per example, this is the HTML which is generated:

<li class="error">
  <!--if list has class error, then add also class error to span which is part of that list tag-->
  <span class="error"></span>
</li>

This is the code I have so far:

if(status == 'error') {
  data.context.addClass('error'); // adds class error to li tag                 
}

Advertisement

Answer

This is easy using JQuery, just select all li items that have the class .error and then use find() to find all the spam elements inside it, finally add the class .error to those:

$(document).ready(function()
{
    $("li.error").find("span").addClass("error");
});
span.error {
    background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<li class="">
    <span>Parent "li" do not have class error</span>
</li>
<li class="error">
    <span>Parent "li" have class error</span>
</li>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement