Home > Blockchain >  how to modify id2 background color with id1 content
how to modify id2 background color with id1 content

Time:07-16

if( $("#infotitle1:contains('all')") ){
    $("#bouton1").css( "background-color", "#BEBEBE" );
}   
else if ( $("#infotitle1:contains('claims')") ){
    $("#bouton1").css( "background-color", "#FF8B00" );
}  
else {
    $("#bouton1").css( "background-color", "red" );
}

I would like to modify the backgroundcolor of #bouton1 depending on the content of #infotitle1

my code do not work, can anybody help ?

CodePudding user response:

You can explore the text() and indexOf() functions.

The .text() method returns a string containing text in the matched element.

Once you get the entire text inside an element, you can use indexOf to check if string contains substring.

if ($("#infotitle1").text().indexOf("all") >= 0) {
    $("#bouton1").css( "background-color", "#BEBEBE" );
} else if ($("#infotitle1").text().indexOf("claims") >= 0) {
  $("#bouton1").css( "background-color", "#FF8B00" );
}
else {
  $("#bouton1").css( "background-color", "red" );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="infotitle1">claims</div>
<div id="bouton1">George Martin</div>

CodePudding user response:

Checking if a given selector returns an object required a further step.. in this case I check for the length > 0 for example.

I slightly modified your code to make the ids as parameters so that I could show all the outcomes:

styleButton('bouton1','infotitle1');
styleButton('bouton2','infotitle2');
styleButton('bouton3','infotitle3');

function styleButton(idButton, idTitle){
  if( $(`#${idTitle}:contains(all)`).length > 0 ){
    $(`#${idButton}`).css( "background-color", "#BEBEBE" );          
  }   
  else if ( $(`#${idTitle}:contains(claims)`).length > 0 ){
    $(`#${idButton}`).css( "background-color", "#FF8B00" );          
  }  
  else {
    $(`#${idButton}`).css( "background-color", "red" );         
  }  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="infotitle1">all</div>
<button id="bouton1">Button1</button>

<div id="infotitle2">claims</div>
<button id="bouton2">Button2</button>

<div id="infotitle3">other</div>
<button id="bouton3">Button3</button>

  • Related