Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I always assumed JavaScript passed copies of variables to functions - so while this code works I'm not sure why - the dynamically created element is not being returned. should the function stylepara not be working with a copy of the created paragraph?

Thanks

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dynamically Create</title>
<script>
function create()
{
	var x = document.createElement('p');
	var paragraphText = document.createTextNode("Dynamically Created Paragraph");
	x.appendChild(paragraphText);
	stylepara(x);
	document.body.appendChild(x);
}

function stylepara(para)
{
	para.style.backgroundColor="orange";
	para.style.fontFamily="calibri";
	para.style.fontSize="32px";
	para.style.color="red";
	return(true);
}

</script>
</head>
<body onload = "create()">
</body>
</html>
Posted
Comments
Kornfeld Eliyahu Peter 10-Nov-14 4:23am    
I can't see the problem! This code adds a new paragraph, with text and formatting, to the body content...
jaket-cp 10-Nov-14 4:50am    
Have a read of http://snook.ca/archives/javascript/javascript_pass
Hope it helps.
BrianHamilton 10-Nov-14 5:59am    
Objects are passed by reference, not value. Thanks!
jaket-cp 10-Nov-14 6:04am    
no problem :)

1 solution

Your question is not clear and does not corresponds to the issue description.
Create function deos not require any inputs. It is executed every time on load page.

If you want to pass default text to function, change it to:
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dynamically Create</title>
<script>
function create(partext)
{
    var x = document.createElement('p');
    var paragraphText = document.createTextNode(partext);
    x.appendChild(paragraphText);
    stylepara(x);
    document.body.appendChild(x);
}

function stylepara(para)
{
    para.style.backgroundColor="orange";
    para.style.fontFamily="calibri";
    para.style.fontSize="32px";
    para.style.color="red";
    return(true);
}

</script>
</head>
<body onload = "create('A brand new function, WOW!')">
</body>
</html>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900