How to use Json in JQuery to modify multiple attributes?

0 votes
asked Jun 19, 2013 in JQuery by anonymous

If I need to change multiple attribute values at the same time, how do we do that in JQuery? For example, if I need to change the title of the div and the back-ground color and font of that div tag what are the different ways we have in JQuery to achieve this, what would be best approach. Please post me some sample with JSon as well. Thanks.

Share

1 Answer

+1 vote
answered Jun 20, 2013 by anonymous
selected Jun 21, 2013 by administrator
 
Best answer

Lets assume that you have the below html on your page and you want to change the attributes and styles what every you mentioned using JQuery.

<div id="myDiv">
 <h1> Change multiple attributes using JQuery</h1>
 <span>This is my first Jquery code</span>
</div>

Now if you want add some title to to the span and change span background color and font, you can do in couple of ways.

First, you can do it using Chaining function. That is, you are going to execute chain of functions in a single jquery.

Example:

$('#myDiv span').attr('title','span title')
                .css('background-color', 'red')
                .css('font-size', '20pt');

Second method, I can modify the above JQuery to use JSon for multiple attribute instead of separating title and style. When you want to use JSon, then you need put all your properties and its values inside the curly braces.

Syntax : Attribute Name : 'attribute value'

Example:

$('#myDiv span').attr(
               {
                   title : 'span title'
                   style: 'background-color : red; font-size : 20pt'
               });

But I can write the above JQuery in a different way using JSon inside css function. This will cause the chaining but, it is good know that we have this option, so that whenever we want to change only the style , we can use this pattern.

Syntax: 'attribute name' : 'attribute value'

Example:

$('#myDiv span').attr('title','span title')
                .css(
                    {
                        'background-color' : 'red',
                        'font-size' : '20pt'
                    });

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...