Can anyone tell me how to add <a>
tag and href inside it using JavaScript?
I am using:
document.createElement('a').setAttribute('href', '#');
But it doesn't seem to work.
Can anyone tell me how to add <a>
tag and href inside it using JavaScript?
I am using:
document.createElement('a').setAttribute('href', '#');
But it doesn't seem to work.
You create a node, but you do not assign the node to an element in the browser.
var a = document.createElement('a'); // generate node
a.setAttribute('href', '#'); // set attribute
a.textContent = 'foo'; // assign some text
// or use
// a.innerHTML = 'foo';
document.body.appendChild(a); // use the node
This is the way to create anchor use createElement() and setAttribute() and then appendChild() to append it to your div
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.textContent= "link text";
mydiv.appendChild(aTag);
Did you try to append it in the DOM ?
var link = document.createElement('a');
link.setAttribute('href', '#link-here');
link.textContent = 'clickme';
document.body.appendChild(link);
What you have is just the part that creates the new element. Your new hyperlink needs to have some content inside it though.
After that, you must decide where you want it to appear within the document and place it there.
Here's an example:
var newA = document.createElement('a'); // Create the new element
newA.setAttribute('href', '#'); // configure its href attribute
newA.textContent = "Click Me"; // Set content for element
// Insert the new element inside the second div
document.getElementById("d2").appendChild(newA);
<div id="d1">some content</div>
<div id="d2">some content</div>
<div id="d3">some content</div>
Using just createElement() will not help. You have to add it to the document.
Check this example :
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode("CLICK ME"); // Create a text node
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn); // Append <button> to <body>
Source : https://www.w3schools.com/jsref/met_document_createelement.asp
For your problem :
var newDiv = document.getElementById("newDiv");
var anchorTag = document.createElement('a');
anchorTag.setAttribute('href',"mylink.html");
anchorTag.innerHTML = "link text";
newDiv.appendChild(anchorTag);
Here, newDiv is the div where you want to add the anchor.