Reputation: 104
Could I use a variable attribute value to set CSS property? This is because I have one button input which are defined in a for loop coming from backend (python). For example how can I do this:
x = clicked_object.getAttribute('btnid');
$("button[attr1=x]").css('background-color', 'green');
Obviously, I can write if conditions but too much programming, looking for a smarter way.
Upvotes: 3
Views: 77
Reputation: 2987
Yes but you must concat the string like this:
x = clicked_object.getAttribute('btnid');
$(`button[attr1='${x}']`).css('background-color', 'green');
Upvotes: 0
Reputation: 30390
You can achieve that by constructing a selector that captures a particular attribute with corresponding value like so:
var x = "green";
var y = "blue";
var z = "orange";
$('button[attr1="' + x + '"]').css('background-color', 'green');
$('button[attr2="' + y + '"]').css('background-color', 'blue');
$('button[attr3="' + z + '"]').css('background-color', 'orange');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button attr1="green">Button 1</button>
<button attr2="blue">Button 2</button>
<button attr3="orange">Button 3</button>
Upvotes: 1