How to Center a JavaScript-Created Object

Google is your friend (as is StackOverflow when you're programming):
javascript - CreateElement with id? - Stack Overflow

Several options there. You already have the instance object of redbtn tho when you created it...so you can also just do "redbtn.className=" and set the class there as well.

Okay, I have tried the redbtn.className="", and then set the class property "text-align:center;" in the css. Here is the code:

Javascript:

Code:
function change() {
	var p= document.getElementById("main");

	switch(p.innerHTML)	{
		case "Lines of Story <br> Presented by Cameron Palmer":
		p.innerHTML="This is a text-based game.";
		break;

		case "This is a text-based game.":
		p.innerHTML="It will be very boring.";
		break;

		case "It will be very boring.":
		p.innerHTML="It's made for old people and nerds.";
		break;

		case "It's made for old people and nerds.":
		p.innerHTML="Ahh... text based games.";
		break;

		case "Ahh... text based games.":
		p.innerHTML="Chapter 1<br>Which color do you like more?";
		var redbtn = document.createElement("BUTTON");
		var redtext = document.createTextNode("Red");
		redbtn.appendChild(redtext);
		document.body.appendChild(redbtn);
		redbtn.style.color="red";
		redbtn.className="redbtn";
		break;



	}
}


CSS:

Code:
.redbtn{text-align: center;}
 
Okay, so I checked in the Chrome tools and the class IS being applied to the button, but the center is not taking effect?
 
Ok, sorry about that, forgot you need to add the button in a wrapper DIV.

Change your class name to reflect that. Then apply the class to a div. Add the redbtn to your wrapper div instead of to your body.
 
Ok, sorry about that, forgot you need to add the button in a wrapper DIV.

Change your class name to reflect that. Then apply the class to a div. Add the redbtn to your wrapper div instead of to your body.

Okay, now when I appendChild the button to the div, what do I replace "body" with?

Code:
document.body.appendChild(redbtn);
 
Assign an ID to your wrapper div and do your getElementByID on your wrapper div. Then you can do the ".appendChild" on your wrapper div object.
 
Back
Top Bottom