Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add HTML tag into JavaScript?

I want to make use of one html tag into my javascript but don't know how to make use of that.

For ex: <p>An absolute URL: <a href="https://www.w3schools.com">W3Schools</a></p>

This is my tag. I want to store this into some variable so I can make use of that later in my function. But I don't how to store it. On way I got to store like

var htm = { html : <p>An absolute URL: <a href="https://www.w3schools.com">W3Schools</a></p>}

But again this is an object I can not use the perticular anchor tag. Can anybody please suggest how to deal with it. How to store html tags in JavaScript variable or any solutions.

like image 434
David Avatar asked Apr 20 '26 04:04

David


2 Answers

    
function createCustomElement(anchorText, anchorLink){
  

  var aTag = document.createElement("a");
  aTag.href = anchorLink;
  aTag.innerHTML = anchorText;
  
  return aTag ;
}

var parent = document.getElementById('para');
var customElement = createCustomElement("w3Schools", "www.w3School.com");
parent.appendChild(customElement);
<div id="para">
</div>
like image 50
ArunBabuVijayanath Avatar answered Apr 21 '26 18:04

ArunBabuVijayanath


We can assign the string template directly by calling innerHTML on a newly created element and returning its childNode. By doing so we can add custom attributes to the new DOM element as well by adding it to the template string.

function strToElem(text, link){
  var temp = '<p> An absolute URL : <a href="'+ link + '">'+text+'</a></p>';
  var a = document.createElement("p");
  a.innerHTML = temp;
  return a.childNodes[0];
}

var parent = document.getElementById('parent');
var elem = strToElem("w3Schools", "www.w3School.com");
parent.appendChild(elem);
<div id="parent">
</div>
like image 38
Dan Philip Avatar answered Apr 21 '26 17:04

Dan Philip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!