I am totally new at javascript and am trying to create a dynamic list in JavaScript that is both a hyperlink to and shows the text string of a tag in my html code that has the id = v1. Kind of like a menu to different parts of that same webpage.
I have tried to do this using document fragments (https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#document_fragments) but it is not working and I don't have any idea of how to insert the text string of the in the "menu".
Here is part of my code:
var container = document.getElementById("contentarea");
var header = document.getElementById("v1");
for (i = 0; i < length.header; i++) {
$(document.createElement("li")).li;
$(document.createElement("a")).link.append(li)( {
href: "#v1"
})
list.appendChild(li);
container.appendChild(list)
}
You could do something like this
// div to get the textContent from, replace it with whatever you want
const divE = document.getElementById('test');
// our list tag
const list = document.getElementById('list');
// looping
for (let i = 0; i < 4; i++) {
const listEl = document.createElement('li'); // our list element
const aTag = document.createElement('a'); // a new <a> tag to append link
const linkTag = document.createElement('link'); //new link tag
linkTag.href = '#test'; // setting hyperlink
aTag.textContent = divE.textContent // setting the textContent for <a> tag
aTag.appendChild(linkTag); // appending link to the a tag
listEl.appendChild(aTag); // appending a tag to the <li> tag
list.appendChild(listEl) // finally appending our list element to the main list
}
<div id="test">Something here</div>
<ul id="list"></ul>
// Create element
const loi = document.createElement('li');
// Add class
loi.className = 'collection-item';
// Add id
loi.id = 'new-item';
// Add attribute
loi.setAttribute('title', 'New Item');
// Create text node and append
loi.appendChild(document.createTextNode('Hello World'));
// Create new link element
const link = document.createElement('a');
// Add classes
link.className = 'delete-item secondary-content';
// Add icon HTML
link.innerHTML = '<i class="fa fa-remove"></i>';
// Append link into li
loi.appendChild(link);
// Append li as child to ul
document.querySelector('ul.collection').appendChild(loi);
console.log(loi);
Here when I want to update the text-node which is hello-world, by writing loi.textContent="ghg"; then that hello world is changed to ghg, but I missed those anchor tag, and I tag which I have created apart from this everything is there, I have attached the output screenshot also.
When you are inserting a text node into li, it is the first child of li like you mentioned. You can access it with loi.childNodes[0] or use the read-only attribute loi.firstChild to verify.
const loi = document.createElement('li');
// Add class
loi.className = 'collection-item';
// Add id
loi.id = 'new-item';
// Add attribute
loi.setAttribute('title', 'New Item');
// Create text node and append
//const span = document.createElement("span");
//const text = document.createTextNode("Hello World");
//span.appendChild(text);
loi.appendChild(document.createTextNode("Hello World"));
// Create new link element
const link = document.createElement('a');
// Add classes
link.className = 'delete-item secondary-content';
// Add icon HTML
link.innerHTML = '<i class="fa fa-remove"></i>';
// Append link into li
loi.appendChild(link);
// Append li as child to ul
document.querySelector('ul.collection').appendChild(loi);
const newText = document.createTextNode("New World");
console.log(loi.childNodes[0]);
loi.childNodes[0].replaceWith(newText);
//OR loi.replaceChild(newText, loi.childNodes[0]);
<ul class="collection"></ul>
Can someone help me on how to add anchor link/ onclick to a datarow
for(i=0;i<10;i++){
dataRow1 = dataRow.insertCell(0);
record = document.createTextNode(returnedValues[i].Name);
dataRow1.appendChild(record);
}
Your question is not clear, I assume this might be helpful:
// Create anchor tag
const a = document.createElement('a');
// Add link
a.href = 'http://yourlink.com';
// Add Text
a.innerText = 'Custom Link';
// `dataRow` should be a HTML Element
dataRow.appendChild(a);
How can I make the text in the div (the content of the variable name) become a link? In other words: To change the style to "a" without using jQuery.
var newtit=document.createElement('div');
newtit.id=name; // name is a variable
newtit.innerHTML= name;
document.getElementById("w3c").appendChild(newtit);
Just do what you did with a div, but instead of creating a div, create an anchor element. Add the link you want as the href-attribute.
var newtit=document.createElement('a');
newtit.href = "http://www.google.com"
newtit.innerHTML= "linkylink";
document.getElementById("w3c").appendChild(newtit);
Based on your content, first create the div then append the anchor element to it
var tab = document.createElement("div");
tab.id = "TabX";
document.getElementById("w3c").appendChild("tab");
var link = document.createElement("a");
link.href = "#TabX";
link.innerText = "Tab XX";
document.getElementById("TabX").appendChild("tab");
or just write the anchor straight to the inner HTML
tab.innerHTML = "<a href='#TabX'>Tab XX</a>"
I have a string for a title and a string for a link. I'm not sure how to put the two together to create a link on a page using JavaScript. Any help is appreciated.
The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs. I would like to link the titles to the URL to make the page useful.
I am using jQuery but am completely new to it and wasn't aware it could help in this situation.
<html>
<head></head>
<body>
<script>
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
</script>
</body>
</html>
With JavaScript
var a = document.createElement('a');
a.setAttribute('href',desiredLink);
a.innerHTML = desiredText;
// apend the anchor to the body
// of course you can append it almost to any other dom element
document.getElementsByTagName('body')[0].appendChild(a);
document.getElementsByTagName('body')[0].innerHTML += ''+desiredText+'';
or, as suggested by #travis :
document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
<script type="text/javascript">
//note that this case can be used only inside the "body" element
document.write(''+desiredText+'');
</script>
With JQuery
$(''+desiredText+'').appendTo($('body'));
$('body').append($(''+desiredText+''));
var a = $('<a />');
a.attr('href',desiredLink);
a.text(desiredText);
$('body').append(a);
In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.
Create links using JavaScript:
<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>
OR
<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>
OR
<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>
There are a couple of ways:
If you want to use raw Javascript (without a helper like JQuery), then you could do something like:
var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";
// and append it to where you'd like it to go:
document.body.appendChild(element);
The other method is to write the link directly into the document:
document.write("<a href='" + link + "'>" + text + "</a>");
<script>
_$ = document.querySelector .bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement( 'a' )
a.text = "Download example"
a.href = "//bit\.do/DeezerDL"
AppendLinkHere.appendChild( a )
// a.title = 'Well well ...
a.setAttribute( 'title',
'Well well that\'s a link'
);
</script>
The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear!
Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")
Leave the protocol open.
Instead of http://example.com/path consider to just use //example.com/path.
Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.
OffTopic: That's not really relevant about creating links in JS
but maybe good to know:
Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.
Dynamically create a hyperlink with raw JavaScript:
var anchorElem = document.createElement('a');
anchorElem.setAttribute("href", yourLink);
anchorElem.innerHTML = yourLinkText;
document.body.appendChild(anchorElem); // append your new link to the body
A dirty but quick way to create elements:
const linkHTML = `<a
class="my-link"
style="position: absolute; right: 0"
href="https://old.reddit.com"
title="Go to old reddit"
>
Old Reddit
</a>`;
// create element
const linkEl = strToElement(linkHTML);
// add element to document.body
document.body.appendChild(linkEl);
// utility function that converts a string to HTML element
function strToElement(s) {
let e = document.createElement('div');
const r = document.createRange();
r.selectNodeContents(e);
const f = r.createContextualFragment(s);
e.appendChild(f);
e = e.firstElementChild;
return e;
}
You paste this inside :
Click here