Reputation: 20544
I'm trying change the background color from multiple buttons based of their inner text using jQuery. It was easy enough to do with straight javascript using a for loop but I can't figure out how to do the same thing in jQuery.
Here's where I'm at:
$('button').click(function(){
$(body).css('background-color', "$('button').text()");
});
Upvotes: 1
Views: 513
Reputation: 9813
body
is an element, so either use document.body
, or use "body"
to select it.this
should be the button you clicked, just wrap it with jquery and call .text()
on it. $(body).css('background-color', "$('button').text()");
will try to set the string "$('button').text()"
to background-color
, jquery won't try to parse it and get the value from it for you.$('button').click(function(){
$('body').css('background-color', $(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>red</button>
<button>blue</button>
Upvotes: 1
Reputation: 207511
You are setting it to a string, not the value of the text. And you want to use this
to get a reference to the element that was clicked. Just using $("button")
would return the text of the first button.
$('button').click(function(){
$(body).css('background-color', $(this).text());
});
Upvotes: 2