3

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.

3
  • Yes, you are talking about attribute selectors developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors Commented Aug 6, 2019 at 2:14
  • 2
    Could you add more context, it is not too clear what you need. Anyway, I believe, you wanted to write $("button[attr1=" + x + "]").css('background-color', 'green'); instead of $("button[attr1=x]").css('background-color', 'green');. Or, if you are able to use template literals: $(`button[attr1=${x}]`).css('background-color', 'green'); Commented Aug 6, 2019 at 2:16
  • Well, I did not know if correct way is $("button[attr1=" + x + "]").css('background-color', 'green'); , you were right tho. This is the right way. Commented Aug 6, 2019 at 2:24

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Shidersz on the comments offered the same solution which worked!
@Hans glad I could help :)
0

Yes but you must concat the string like this:

x = clicked_object.getAttribute('btnid');
$(`button[attr1='${x}']`).css('background-color', 'green');

2 Comments

Yes, i forgot the " " mark that wrap the value, updated
Hmm, weird, can you please try change it to single quote to see if it works ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.