Home » Javascript » How to add HTML class based on the contents of another element?

How to add HTML class based on the contents of another element?

Posted by: admin October 18, 2018 Leave a comment

Questions:

I am trying to add an HTML class to a particular element based on the content of another element. This element’s data is dynamic. Here is my code:

<div class="container-fluid">
    <div class="row">
        <div class="task_list col-lg-12 col-sm-12">

            @foreach($tasks as $task)

            <div id="{{ $task->id }}" class="row task_element">

                <p class="task_description">
                    {{ $task->description }}
                </p>

                <p class="task_priority">
                    {{ $task->priority }}
                </p>

            </div>

            @endforeach

        </div>  
    </div>
</div>

<script>

    if ($(".task_priority").text().trim() === "high") {
        $(".task_element").addClass('high');
    } elseif ($(".task_priority").text().trim() === "medium") {
        $(".task_element").addClass('medium');
    } else ($(".task_priority").text().trim() === "low") {
        $(".task_element").addClass('low');

</script>

This is currently not working. It seems like a simple task, but I have not been able to find out how to solve it. How do I add a class to the “task_element” div based on the text value of “task_priority”?

Answers: