0

Ok basically I want to store part of body tag inside a variable in function and call the function in the body to create that part of the HTML. Here's my code for the function:

 function RadioButtonContent()
 {
var rbc = '<h3>Type your radio button here:</h3><input type="text" name="option" id="option" value="Example 1" /><button id="AddButton" onclick="radio()">Add</button><button id="RemoveButton">Remove</button><div id="updateDivRadio"><h1>Space for Radio Button</h1></div>'
var rbcAppen = document.getElementById('radioButton');
rbc.appendChild.rbcAppen;
 }

But it doesn't do anything when called... may be DOM doesnt work this way or is there a way around? Here's the fiddle.

Please help

3
  • You may want to use the innerHTML property if you're looking to do this. Commented Mar 31, 2014 at 17:16
  • Yeah I have a feeling that might be the case... any ideas how? @Seiyria Commented Mar 31, 2014 at 17:20
  • I would use a hybrid of my statement and the answer below, I'll post it in a moment. Commented Mar 31, 2014 at 17:20

2 Answers 2

1

See https://developer.mozilla.org/en-US/docs/Web/API/document.createTextNode

// For text only
rbcAppen.appendChild(document.createTextNode(rbc))

// If you can overwrite the HTML in rbcAppen
rbcAppen.innerHTML = rbc;

// If you  can't overwrite the HTML, create a temporary node, add 
// the content there and append the nodes  to your rbcAppen
var tempNode = document.createElement("div");
tempNode.innerHTML = rbc;
while (tempNode.childNodes.length) {
    rbcAppen.appendChild(tempNode.childNodes[0]);
}

Working code

Sign up to request clarification or add additional context in comments.

3 Comments

thanks.. rbcAppen.appendChild(document.createTextNode(rbc)) works but it doesnt put the content as html element and tags, instead it puts them just as plain text, which is not my intention...
@envyM6 I've updated the answer to cover other cases
Awesome @Juan Mendes... your fiddle actually works!! Please have a look at this
0

You could make a new node and set its HTML, like so:

var newNode = document.createElement("div")
newNode.innerHTML = rbc;
rbcAppen.appendChild(newNode);

Here's a fiddle: http://jsbin.com/cebikuxi/1/edit

18 Comments

Here is the fiddle with your code @Seiyria... not working :(
I'm getting Uncaught ReferenceError: RadioButtonContent is not defined on your fiddle. I'll see if I can get a fix going.
@envyM6 I'm also using chrome and getting that error. Hmm.
That's because the jsfiddle was wrapping RadioButtonContent in an onload See jsfiddle.net/mendesjuan/WYf3G/2. You cannot create a text node from HTML
LOL may be my PC is drunk then... :P But seriously im not getting error
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.