Matt Kaplan
Matt Kaplan

Reputation: 45

How to assign a variable value to an HTML input created in Javascript / How to style HTML elements in Javascript

Here's the code I am currently using.

function firstChildAge() {
  var header = document.createElement('H1');
  var body = document.getElementsByTagName('BODY');
  var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
  var inputChildOne = document.createElement("Input");
  header.appendChild(textnode);
  document.body.appendChild(header);
  document.body.appendChild(inputChildOne);
}

a) How would I assign a variable value to the response created by the user to the Input?

b) How can I style elements inside Javascript? For example, how can I make the text "WHAT IS THE AGE OF THE FIRST CHILD?" red, or change the font size?

Thank you!!!

Upvotes: 1

Views: 183

Answers (2)

PotatoManager
PotatoManager

Reputation: 1775

You can retrieve the current string of the input box using.

var val=document.getElementById('id of the input').value;//you can use any other element selection method too

to set the color you can use

document.getElementById('id of the tag').style.color='color name or hex';

You can use this to set the id of an element

element.setAttribute("id", "uniqueIdentifier"); 

Also textNodes dont have style attributes, they take the parent elements features like this

var header = document.createElement('H1');
     var body = document.getElementsByTagName('BODY');
     var span = document.createElement('span');
     // Set DOM property
     span.style.color = 'red';
  span.appendChild(document.createTextNode('WHAT IS THE AGE OF THE FIRST CHILD'));

 // Add to document
 document.body.appendChild(span);

 var inputChildOne = document.createElement("Input");

 header.appendChild(textnode);
 document.body.appendChild(header);
 document.body.appendChild(inputChildOne);

Upvotes: 1

Kermit
Kermit

Reputation: 1062

a) you can use document.getElementById('id of input').value = variableValue

b) you can use document.getElementById('id of tag').style.styleName = val,for example, using document.getElementById('id of tag').style.color = 'red' to set color,using document.getElementById('id of tag').style['font-size'] = '14px' to set font-size

Upvotes: 1

Related Questions