You are trying to mix some concepts here.
The normal way of adding DOM Nodes (that is what you are creating with document.createElement
to the DOM is by appending with appendChild
.
By using innerText
on the other hand, you are just setting the text
value for one element. You cannot simply add another DOM element, like ${myAttribute}
inside. That is why you don't see it in between.
There are some ways to work around this.
1) If you need to work with just nodes, go all the way with DOM nodes and also create text nodes. For your example, you could create 2 text nodes for the text, and the anchor node, and add all of them to the h1
in proper order, like this:
let myElement = document.createElement("h1");
let textNode1 = document.createTextNode("subscribe ");
let textNode2 = document.createTextNode(" here");
let myAttribute = document.createElement("a");
myAttribute.innerText = "noobie";
myAttribute.classList.add("decoration");
myAttribute.setAttribute("href", "www.peo.com");
myElement.appendChild(textNode1);
myElement.appendChild(myAttribute);
myElement.appendChild(textNode2);
document.body.appendChild(myElement);
2) Add the whole h1 content via innerHTML
, where you can set HTML values. Now there is not a straight forward way to convert a DOM node to HTML, so you should maybe write HTML directly and not create a DOM node from it (see below for how to create HTML from a DOM node). I don't know about your specific use case to determine what is your preferred option:
let myElement = document.createElement("h1");
myElement.innerHTML = `suscribe <a href="www.peo.com" class="decoration">noobie</a> here`;
document.body.appendChild(myElement);
See https://www.w3schools.com/jsref/prop_html_innerhtml.asp
If you don't want to or cannot write the HTML like that you could get to the HTML of your DOM node by wrapping it in another element and then getting the innerHTML
of that wrapper node. You can see how that can be done in the following answer:
How to get the HTML for a DOM element in javascript
That way you can still create your link via createElement
but you don't need to create text nodes for text.
It really depends on your context what is the best option for you.
. like this :
– dil. 1122 Jun 15 '20 at 13:36suscribe noobie here