Change Class according to ID

Asked

Viewed 116 times

1

I have the following structure.

<div id="cabecalho">
 <span data-bind="attr: { id: solicitacao.numero}"></span>
<div>

where, request returns me a number from 1 to 10 i would like to add a class according to the number.

Example:

if( span == 1 )
{
  $("cabecalho").children.addClass( "teste1" );
}
  • A question. Why don’t you direct it? In the class attribute you put the direct value instead of doing it later via Jquery?

1 answer

1


Use the jQuery date function to pick up the data-bind value and check with the number, like this:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    .class1{background:red}
    .class2{background:blue}

    </style>
    </head>
    <body>
      <span data-bind="1" class="">Oi</span>
      <span data-bind="2" class="">Olá</span>


        	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        	<script>                                        
              $(document).ready(function(e) {
                  $('span').each(function(index, el) {
                      if($(this).data('bind') === 1){
                          $(this).addClass('class1');
                      }else{
                          $(this).addClass('class2');
                      }
                  });

              });
          </script>
    </body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.