Daan Seuntjens
Daan Seuntjens

Reputation: 960

How to add subscript (the html <sub> tag) programmatically?

I'm trying to add subscript programmatically using javascript. I'm using the .sub(); command in javascript.

My expected outcome:

<p>a = b + r<sub>1</sub></p>

My code:

function addSubscript(){
  var text = 'a = b + r' + '1'.sub();
  var para = document.createElement("p");
  var text_p1 = document.createTextNode(text);
  para.appendChild(text_p1);
  
  document.getElementById("print").appendChild(para);
}
button{
   width: 20%;
   margin-left: 40%;
}
#print{
   width: 100%;
   text-align: center;
}
<button onclick="addSubscript()">Add subscript</button>
<div id="print"></div>

How can I fix this?

Upvotes: 3

Views: 808

Answers (2)

Trupti Shetty
Trupti Shetty

Reputation: 66

You can simple write HTML content in the innerHTML & while rendering, it will render with HTML properties. For example here, you can use - < sub > tag itself

function addSubscript(){
  var text = 'a = b + r' + '<sub>'+'1'+'</sub>';
  var para = document.createElement("p");
  para.innerHTML = text;
  
  document.getElementById("print").appendChild(para);
}
button {
  font-size: 18px;
  width: 100%;
  height: 26px;
}
#print {
  font-size: 16px;
  width: 100%;
  text-align: center;
}
<button onclick="addSubscript()">Add subscript</button>
<div id="print"></div>

Upvotes: 2

Maxime Launois
Maxime Launois

Reputation: 958

Content inside text nodes render as-is, without formatting. To apply a subscript use innerHTML:

function addSubscript(){
  var text = 'a = b + r' + '1'.sub();
  var para = document.createElement("p");
  para.innerHTML = text;
  
  document.getElementById("print").appendChild(para);
}
button {
  font-size: 18px;
  width: 100%;
  height: 26px;
}
#print {
  font-size: 16px;
  width: 100%;
  text-align: center;
}
<button onclick="addSubscript()">Add subscript</button>
<div id="print"></div>

Upvotes: 4

Related Questions