/    Sign up×
Community /Pin to ProfileBookmark

how to assign variable value to jquery?

var s=”attr”
var i=$(s)
// jQuery(elem).attr(attr,eval(“elm”+attr));
jQuery(elem).$(s)(attr,eval(“elm”+attr));//i tried this.

how to assign a variable name in the above code(in place of s) so that i need to add an attribute to the element “elem”.

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@aj_nscFeb 18.2012 — It could be just me, but I'm not even remotely sure about what you're trying to do.

Are you trying to assign a jQuery object as an attribute on another elem?

Whatever you're trying to do, I'm sure I'll be able to help you out, your code has utterly confused me, however (someone else may understand easily what I haven't been able to discern). Maybe if you try explaining again in a few more words, I'll be able to help you better.

EDIT: Are you trying to assign an attribute on one element to an attribute on another element?
Copy linkTweet thisAlerts:
@ammuhereauthorFeb 18.2012 — No.i m not trying to assign an attribute on one element to an attribute on another element.

Please see the more detailed code.


var elmlist={

"div": [
{
"div": "div"
},
{
"attr": [
"id": "id" ]
},
"css": [
{
"backgroundcolor": "background-color",
"textalign": "text-align"
}
]
},
{}
]

};

var nodelist={ "nodename":"css" ,"nodename":"attr"}

traverse(elmlist["div"]);

function traverse(propertylist){

for(var node in nodelist){

for (var attr in propertylist)

if(jQuery.type(propertylist[attr])=="string")

{


jQuery(elem).nodelist[node](attr,eval("elm"+attr));//need modification here

//jQuery(elem).css("background-color","orange");//like this

}

}

} } [/QUOTE]



jQuery(elem).nodelist[node](attr,eval("elm"+attr)):- in this from the nodelist[node] i can get the value of "attr" in the first time and second time "css". Please let me know if any more clarification needed and help me how to resolve this.
Copy linkTweet thisAlerts:
@aj_nscFeb 18.2012 — Well, theoretically, the following code achieves what you are trying:
<i>
</i>jQuery(elem)[nodelist[node]]('attributename','attributeval);


HOWEVER, take a look at this object:

<i>
</i>var nodelist = {
"nodename" : "attr",
"nodename" : "css"
}


What happens if I do this:

<i>
</i>console.log(nodelist.nodename);


See what I mean? You're overwriting properties. You should use an array:

<i>
</i>var nodelist = ['attr','css'];


I just want to throw it out there that I think your code is ridiculously complex, however. What is it that you are trying to achieve in an overall sense?
Copy linkTweet thisAlerts:
@ammuhereauthorFeb 18.2012 — i want to create DOM elements dynamically using jQuery.

so when i called something like this..
[CODE]var element_wrapper=$.create('div','divtest','','','yes','orange','center','');[/CODE]
it should create div tag with all the attributes and style which are passing to the extended jQuery function as parameters.

I am giving the whole function below which i hope will give you some idea on what i am trying to do.

[CODE]jQuery.create = function(elmtype,elmid,elmclass,elmchecked,elmstyle,elmbackgroundcolor,elmtextalign,elmtext) {
var args = arguments[0] || {}, elem = null;

var objname=elmlist[args]
if (args.constructor == String) {
if (arguments.length > 1) {
var typelist = objname[0];

for(var type in typelist)
{elem = document.createElement(type);
}
traverse(objname[1]);
function traverse(propertylist){
var nodelist={ "nodename":"css" ,"nodename":"attr"}
for(var node in nodelist){
for (var attr in propertylist)
if(jQuery.type(propertylist[attr])=="string")
{
jQuery(elem).nodelist[node](attr,eval("elm"+attr));
}
else{
// jQuery(elem).css("background-color","orange");
traverse(propertylist[attr]);
}
}

}

if ( !( jQuery.isEmptyObject(objname[2])))
{
for(var value in objname[2])
{elem = document.createTextNode(eval("elm"+value));
}

}

}
} return elem;
};[/CODE]


so i want to call the jQuery Function .attr and .css dynamically, as per the value that passed to the variable nodelist[node]. For that i used

jQuery(elem).nodelist[node](attr,eval("elm"+attr)); where nodelist have two values attr and css.

in my code everything works fine except the part of nodelist[node].

ie: 1. jQuery(elem).attr(attr,eval("elm"+attr));

and 2. jQuery(elem).css(attr,eval("elm"+attr)); is working fine.

so i assigned the values to an object and accessed it while creating the attributes.
[CODE] var nodelist={ "nodename":"css" ,"nodename":"attr"}[/CODE]
So my question is how to refer a variable to call a function in jQuery?
Copy linkTweet thisAlerts:
@aj_nscFeb 18.2012 — You can dynamically create DOM elements in jQuery very easily like this:

<i>
</i>var myDOMElement = $('&lt;div id="myid" style="background-color: #f00; text-align: center;"&gt;&lt;em&gt;A new dom element&lt;/em&gt;&lt;/div&gt;');


For the record, you have to call methods using a variable using square bracket notation followed by parentheses and arguments like this:

<i>
</i>jQuery(elem)[methodname](argument1,argument2);
Copy linkTweet thisAlerts:
@ammuhereauthorFeb 19.2012 — i had approached this method first time..But as i heard using concatenated string in jquery have lot of disadvantages i selected this method.

Also how to pass a value to the methodname in ur below code?

jQuery(elem)[methodname](argument1,argument2);
Copy linkTweet thisAlerts:
@aj_nscFeb 19.2012 — But as i heard using concatenated string in jquery have lot of disadvantages[/quote]

I'd like to hear them. By looking at your function, it's highly unscalabale and difficult to remember the order of the arguments - is the background color the 6th argument or the 5th?

jQuery(elem)[methodname](argument1,argument2);[/QUOTE]

<i>
</i>//you can call the method using dot notation
jQuery(elem).attr('id','someID');

//you can use a quoted string
jQuery(elem)['attr']('id','someID');

//you can use a variable
var methodname = 'attr';
jQuery(elem)[methodname]('id','someID');
Copy linkTweet thisAlerts:
@ammuhereauthorFeb 20.2012 — thank you so much for your answer.

This helps me.

Also please suggest how to make it more flexible so that when i passed the values to a function it should return the DOM elements as created.
Copy linkTweet thisAlerts:
@aj_nscFeb 20.2012 — As I mentioned, I'd use jQuery's native ability to create DOM elements instead of abstract it into an unscalable function.

Figure out what your CSS properties and attributes are, create a string from it, and then wrap it in the jQuery function and it will return a DOM element:

<i>
</i>$.fn.easyCreateDOM = function(tagname,cssprops,attributes) {

var htmlString = '&lt;div style="';
for(i in cssprops) {
htmlString += i+':'+cssprops[i]+';';
}
htmlString += '" ';

for(i in attributes) {
htmlString += i+'="'+attributes[i]+'"';
}

htmlString += '/&gt;';


return $(htmlString);

}

var CSSProps = {
'background-color' : '#f00',
'text-align': 'center',
'display' : 'inline'
};

var Attributes = {
'id' : 'someElemID',
'class' : 'a-class-name'
};

//myDIV is a jQuery object
var myDIV = $.fn.easyCreateDOM('div',CSSProps,Attributes);
console.log(myDIV);


Hopefully there's no typos, but if there are, it should be fairly evident on what to do to fix them.

EDIT: Edited the code to fix all the typos....?
Copy linkTweet thisAlerts:
@ammuhereauthorFeb 20.2012 — 
var CSSProps = {

'background-color' : '#f00',

'text-align': 'center',

'display' : 'inline'

};

var Attributes = {

'id' : 'someElemID',

'class' : 'a-class-name'

};


[/QUOTE]


ok...just for example i need to create 10 elements which includes a table,tr,td...etc... so for each and every element i need to declare a set of attributes which will again be complicate my code.

for that only i delcare the attribute name as an object array set and passed only the values, which needs to be assign to that variables,of the function.

another apporach is


var element = $.create('li',{

id: 'item',

'class': 'custom-class'

},['This is a new LI element']);

so that while creating the DOM element itself will specify what are the attributes needed along with the element. Which one is more acceptable and flexible?

i had uploaded my latest js file along with this..Please check it and let me know any modification.
Copy linkTweet thisAlerts:
@ammuhereauthorFeb 23.2012 — i have a string with value as shown below.

var node="1.1.1"

i need to replace a character by specifying the position.

For eg:- i need to replace the last one with 2

any help?
Copy linkTweet thisAlerts:
@Jeff_MottFeb 23.2012 — Figure out what your CSS properties and attributes are, create a string from it, and then wrap it in the jQuery function and it will return a DOM element: [/QUOTE]

An alternative:

[code]
var CSSProps = {
'background-color' : '#f00',
'text-align': 'center',
'display' : 'inline'
};

var Attributes = {
'id' : 'someElemID',
'class' : 'a-class-name'
};

var myDIV = $('&lt;div&gt;').css(CSSProps).attr(Attributes);


I haven't tested it, but according to the docs, that ought to work.
×

Success!

Help @ammuhere spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.10,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...