I\'m new in javascript and i don\'t exactly understand how to modify this code to style a div:
function getParameters() {
var searchString = document.getElemen
the variables in the .each(function(){});
function are not custom, they are always id and value.
your function should go like this:
$.each(hash, function (id, value) {
test_div.style[id] = value;
});
here is a FIDDLE
whats going on basically is, that your hash array contains two objects:
1) color {value = "red"}
2) background {value = "yellow}
the each function iterates thought those, the id
will be first time color
ad second time background
and the value will be first time "red"
ad second time "yellow"
so for the first iteration for example, id = 'color' and value ='red' and it will produce:
test_div.style["color"] = "red";
With the javascript function styleDiv you can pass the url string of style (style=value) and the targets (DOM element tag name, id, class). It will find those targets, and set styles.
Kudos to Banana for using element.style[property] = value, i didn't know about it.
jsFiddle link
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Style a Div</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-git2.js'></script>
<style type='text/css'>
input[type=text] {width: 300px;}
</style>
<script type='text/javascript'>//<![CDATA[
$(function(){
styleDiv = function(paramString, target){
param = paramString.split('&');
if (param.length < 1)
return false;
for(i=0; i< param.length; i++){
val = param[i].split('=');
//jQuery(target).css(unescape(val[0]),unescape(val[1]));
targets=document.querySelectorAll(target);
for (t=0; t < targets.length; t++){
targets[t].style[unescape(val[0])] = unescape(val[1]);
}
}
}
jQuery('#cmdSetStyle').click(function(e){
console.log(styleDiv(jQuery('#txtParamStyle').val(),'#target'));
return false;
});
});//]]>
</script>
</head>
<body>
<form id="frmSendStyle" method="get">
<input type="text" id="txtParamStyle" value="color=red&background=yellow" />
<input type="button" id="cmdSetStyle" value="Set Style" />
</form>
<div id="target">
Hello world
</div>
</body>
</html>