How to get and set attribute in jquery

Total Post:39

Points:273
 1582  View(s)
Ratings:
Rate this:

Hi I’m trying to get attribute and then after set attribute

Here is my code

 
<div class="box" style="width:100px;height:300px;background-color:#ffd800;">
    <p>Are you want to jquery</p>
</div>
 
<input type="button" class="btn" value="Green" style="background-color:green;color:#fff;" />
<input type="button" class="btn" value="Red" style="background-color:red;color:#fff;" />
<input type="button" class="btn" value="Blue" style="background-color:blue;color:#fff;" />
 
 
<script>
    $(document).ready(function () {
        $('.btn').click(function () {
            var btnvalue = $(this).getAttribute('value');
            $('.box').setAttribute('style', 'background-color:' + btnvalue);
        });
    });
</script>

 

My question is when click on green button that time box color green and when click red button that time box color red.

My code is not work properly.

  1. Post:45

    Points:315
    Re: How to get and set attribute in jquery

    Hi you can use this code for get and set attribute

    <div class="box" style="width:100px;height:300px;background-color:#ffd800;">
        <p>Are you want to jquery</p>
    </div>
     
    <input type="button" class="btn" value="Green" style="background-color:green;color:#fff;" />
    <input type="button" class="btn" value="Red" style="background-color:red;color:#fff;" />
    <input type="button" class="btn" value="Blue" style="background-color:blue;color:#fff;" />
     
     
    <script>
        $(document).ready(function () {
            $('.btn').click(function () {
     
                //here we get attribute of clicked button
                var btnvalue = $(this).attr('value');
     
                //here we set attribute in box div
                $('.box').attr('style', 'background-color:' + btnvalue);
            });
        });
    </script>

      Modified On Apr-09-2018 01:38:47 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!