Create list with hyperlink (document fragments) as text string - javascript

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>

Related

How to create HTML tags (with content) on the fly with JavaScript?

I am trying to convert this HTML code to be generated by Javascript on the fly for live data.
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
Ive found a few methods like: appendChild, getElementById, innerHTML and so on. Here is what I've tried so far. I can't seem to get the data to show up.
stringy = data2.Items[0].groupName.values[i];
var para = document.createElement("div");
var node = document.createTextNode(stringy);
para.appendChild(node);
var element = document.getElementById("parental");
element.appendChild(para);
//create div and give it a class
para.setAttribute('class', 'dropbtn');
var div = document.createElement("div");
div.setAttribute('class', 'dropdown-content');
para.parentNode.insertBefore(div, para.nextSibling);
//create link tags and give them text
var alinky = document.createElement("a");
alinky.setAttribute('id', 'linky');
document.getElementById('linky').innerHTML = "linky poo"
div.appendChild(alinky);
Hopefully someone could fill in the blanks on getting this HTML code to be reproduced with javascript. Thanks in advance!
EDIT:
I am trying to create a dropdown menu like this:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown_hover
However, I am trying to create multiple dropdown menus, that dynamically change in quantity based on a query to DynamoDB (AWS). therefore I am using javascript to create the html tags.
The problem is that the scope of the query function does not allow me to see the data outside of the query function, or even inject data into it.
For example, if I try to get a button description from the query, and write to it descriptionArray[0] = data2.Items[0].description; so that I can append the button to the dropdown div, it doesn't know which iteration I'm on in the for loop due to scope. In this example, descriptionArray[0] will work, but descriptionArray[i] will not work because the for loop is outside the query.
Here is the entire logic:
//group data
var length = data2.Items[0].groupName.values.length;
// create elements
const dpdown1 = document.createElement('div');
// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');
console.log(dpdown1);
var button = new Array();
var dpdown2 = new Array();
var membersArray = new Array();
var descriptionArray = new Array();
var linksArray = new Array();
var stringy = new Array;
//list groups
for(i = 0; i<length; i++){
// create button, set button attribs
button[i] = document.createElement('button');
button[i].setAttribute('class','dropbtn');
//create dropdown div, set attributes
dpdown2[i] = document.createElement('div');
dpdown2[i].setAttribute('class', 'dropdown-content');
//list of group names
stringy[i] = data2.Items[0].groupName.values[i];
var stringyy = stringy[i];
var desc;
//query group members and description
var docClient1 = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
var identityId = AWS.config.credentials.identityId;
var paramsyy = {
ExpressionAttributeValues: {
":v1": stringyy
},
KeyConditionExpression: "groupName = :v1",
TableName: "group"
};
docClient1.query(paramsyy, function(err, data2) {
if (err) {
console.error(err);
}else{
descriptionArray[0] = data2.Items[0].description;
//traverse members
for(k = 0; k<data2.Items[0].members.values.length; k++){
// create dropdown links of members
membersArray[k] = data2.Items[0].members.values[k];
linksArray[k] = document.createElement('a');
linksArray[k].setAttribute('href', '#')
linksArray[k].innerText = membersArray[k];
// nest into dpdown2 div, set dpdown2 attribs
dpdown2[0].appendChild(linksArray[k]);
}
}
});
button[i].innerText = stringyy + ": " + descriptionArray[0];
// nest into dpdown1
dpdown1.appendChild(button[i]);
dpdown1.appendChild(dpdown2[i]);
}
// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);
if I use the I from the first for loop inside the query function, it will give me undefined results.
here's how you can do it with vanilla JavaScipt, there are multiple ways to do it, but this way only uses 4 methods: createElement, setAttribute, appendChild, and getElementById, and directly sets 1 property: innerText.
// create elements
const dpdown1 = document.createElement('div');
const button = document.createElement('button');
const dpdown2 = document.createElement('div');
const link1 = document.createElement('a');
const link2 = document.createElement('a');
const link3 = document.createElement('a');
// set link attribs
link1.setAttribute('href', '#')
link1.innerText = 'Link 1';
link2.setAttribute('href', '#')
link2.innerText = 'Link 2';
link3.setAttribute('href', '#')
link3.innerText = 'Link 3';
// nest into dpdown2, set dpdown2 attribs
dpdown2.appendChild(link1);
dpdown2.appendChild(link2);
dpdown2.appendChild(link3);
dpdown2.setAttribute('class', 'dropdown-content');
// set button attribs
button.setAttribute('class','dropbtn');
button.innerText = "Dropdown"
// nest into dpdown1
dpdown1.appendChild(button);
dpdown1.appendChild(dpdown2);
// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');
// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);
<div id="target"></div>
You will to append it to something, in this example it's <div id="target"></div> but it could be something else.
Happy coding!
Mainly you are just doing things out of order.
Create the .dropdown <div> with its class.
Complete the .dropbtn <button> with its class and text.
Add the button to the div.
Create the .dropdown-content <div>.
Complete each link with its href attribute and text.
Add each link to the .dropdown-content <div>.
Add the .dropdown-content div to the .dropdown <div>.
Find the parent element in the document.
Append the whole complete .dropdown <div> to the document.
var para = document.createElement("div"); //make .dropdown div
para.setAttribute('class', 'dropdown'); //add .dropdown class to div
var button = document.createElement("button"); //create button
button.setAttribute('class', 'dropbtn'); //add .dropbtn class to button
var node = document.createTextNode('Dropdown'); //create button text
button.appendChild(node); //add text to button
para.appendChild(button); //add button to .dropdown div
var div = document.createElement("div"); //create .dropdown-content div
div.setAttribute('class', 'dropdown-content'); //add .dropdown-content class to div
//repeat for all necessary links
var alinky = document.createElement("a"); //creat link
alinky.setAttribute('href', '#'); //set link href attribute
var alinkyText = document.createTextNode("Link 1"); //create text for link
alinky.appendChild(alinkyText); //add text to link
div.appendChild(alinky); //add link to dropdown div
para.appendChild(div); //add .dropdown-content div to .dropdown div
var element = document.getElementById("parental"); //find parent element
element.parentNode.insertBefore(para, element.nextSibling); //add .dropdown div to the bottom of the parent element
<div id="parental">
</div>

Cannot create multiple list items in javascript

I have the following array:
["uploads-1462948491987.png", "uploads-1462948492004.png"]
What I want to achieve is have an unordered list of anchors (inside list items) with image names. I have done the following:
var uploadsList = document.querySelector('ul'),
imageitem = document.createElement('li'),
anchorTag = document.createElement('a');
anchorTag.setAttribute('href',"#");
var imagesNamesString = "<%= uploads %>";
var imageNames = imagesNamesString.split(',');
imageNames.forEach(function(image) {
anchorTag.innerHTML = image;
uploadsList.appendChild(imageitem.appendChild(anchorTag));
});
console.log(imageNames);
Problem is, the last image is the only one which appears on the list, what may be causing this? Thanks in advance.
Cannot create multiple list items in javascript
Because you're not creating multiple list items. You're creating one:
imageitem = document.createElement('li')
...and then using it:
uploadsList.appendChild(imageitem.appendChild(anchorTag));
where first you append anchorTag to the li, then immediately move it to the uploadsList (because appendChild returns the node appended, not the node you called it on). The same for the anchor, you're reusing one, not creating one for each image.
You need to create the li and anchor in the loop, and append the li, not the anchor:
imageNames.forEach(function(image) {
var li = document.createElement('li');
var anchor = document.createElement('a');
anchor.href = "#"; // No need for `setAttribute
anchor.appendChild(document.createTextNode(image));
li.appendChild(anchor);
uploadsList.appendChild(li);
});
var imageNames = ["uploads-1462948491987.png", "uploads-1462948492004.png"];
var uploadsList = document.querySelector('ul');
imageNames.forEach(function(image) {
var li = document.createElement('li');
var anchor = document.createElement('a');
anchor.href = "#"; // No need for `setAttribute
anchor.appendChild(document.createTextNode(image));
li.appendChild(anchor);
uploadsList.appendChild(li);
});
document.body.appendChild(uploadsList);
<ul></ul>
Note that I replaced the use of innerHTML with:
anchor.appendChild(document.createTextNode(image));
You probably don't want to interpret the image names as HTML. But if you do, just change it back to:
anchor.innerHTML = image;
Or at that point, really, just
imageNames.forEach(function(image) {
var li = document.createElement('li');
li.innerHTML = "<a href='#'>" + image + "</a>";
uploadsList.appendChild(li);
});
var imageNames = ["uploads-1462948491987.png", "uploads-1462948492004.png"];
var uploadsList = document.querySelector('ul');
imageNames.forEach(function(image) {
var li = document.createElement('li');
li.innerHTML = "<a href='#'>" + image + "</a>";
uploadsList.appendChild(li);
});
document.body.appendChild(uploadsList);
<ul></ul>
But I recommend not treating the image names as HTML (unless you actually put HTML in them).
Note that I changed the name anchorTag to anchor. An element is not a tag. A tag is how we define elements textually in HTML. <a> and </a> are tags (a start tag and an end tag, respectively); a is an element.

Identifying which Div was selected with JavaScript

I have an HTML document with 6 Divs, I've written a javascript code that changes the heading depending on which div is selected (6 vars and 6 functions) e.g.
var divSelect = document.getElementById("firstDiv");
divSelect.onclick = function () {
var mainHeading = document.getElementById("heading");
mainHeading.innerHTML = "You have selected the first option";
};
I then have an anchor div which is linking to another HTML page, when it opens I want it to know which div was selected from the first HTML page, and then input a new heading based on the selection.
So I need to know which of the six functions was actioned based on the div that was clicked.
Any help much appreciated.
You can pass it in url query. Passing for example id parameter, like this: http://example.com/secondpage.html?firstpagedivid=firstDiv And then on second page you can parse url to get div id or whatever parameter you passed.
Here you can find how to get url parameter on second page: link
Html:
<div class="clickable" id="firstDiv">first</div>
<div class="clickable" id="secondDiv">second</div>
<div class="clickable" id="thirdDiv">third</div>
<br>
<div id="heading"></div>
<br>
<a id="navigator" href="second.html">Next page</a>
Javascript:
(function() {
var currentSelectedDiv;
var heading = document.getElementById('heading');
var navigator = document.getElementById('navigator');
var divs = document.querySelectorAll('.clickable');
for(var i=0; i<divs.length; i++) {
divs[i].onclick = function(e) {
var target = e.target;
currentSelectedDiv = target.getAttribute('id');
heading.innerHTML = ['You have selected ', currentSelectedDiv].join('');
}
}
navigator.onclick = function(e) {
e.preventDefault();
var a = e.target;
var href = a.getAttribute('href');
href += '?previousPageDivId=' + currentSelectedDiv;
alert(href);
//Just uncomment line below
//document.location.href = href;
}
})();
Here you have working example: https://jsfiddle.net/3wdzh2d4/

find closing anchor tag from the string and add some value

I am trying to find closing anchor tag. And add Icon after the closing tag.The inside value is coming as a string from database.I need to extract the value and append with icon.
For example
<p>This is a paragraph and link testtestdsfasffdtest1fdfdfdfdfd</p>
In the above example I have paragraph tag inside I have two anchor tag.
Actually the result will come as Test added plus icon testdsfasffd & Test1 added plus icon 2 fdfdfdfdfd
First I need to find the closing anchor tag then i need to append the icon from other functions
Current I am trying like this
var string = '<p>This is a paragraph and link testtestdsfasffdtest1fdfdfdfdfd</p>';
I am setting an pattern
var closingAnchor = '</a>';
string.split(closingAnchor);
after this i need to append icon from other function using for loop. I am getting struggle here kindly please help me.
Splitting HTML is normally a bad bad idea. So just do it with the DOM.
var string = '<p>This is a paragraph and link testtestdsfasffdtest1fdfdfdfdfd</p>';
var div = document.createElement("div");
div.innerHTML = string;
var anchors = div.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var text = document.createTextNode(' TEXT TO ADD ');
var sibling = anchors[i].nextSibling;
if(sibling) {
anchors[i].parentNode.insertBefore(text, sibling);
} else {
anchors[i].parentNode.appendChild(text);
}
}
console.log(div.innerHTML);
document.getElementById("out").innerHTML = div.innerHTML;
<div id="out"></div>
Here you are: // for regex, <\/a> for </a>, g for search all
var string = '<p>This is a paragraph and link testtestdsfasffdtest1fdfdfdfdfd</p>';
var output = string.replace(/<\/a>/g, '</a>YOUR APPENDEE');
alert(output);
Hope this helps.

How to hide child elements using javascript

<div id="wpq2">
<div class="subClass">
<a id="linkTO" class="subClass">New Item</a>
or
<a class="subClass">edit</a>
this list
</div>
</div>
i want to hide all the thing except
<a id="linkTO" class="subClass">New Item</a>
I do not have access to html ,
i have to use javascript
i tried somthing
var parentID = document.getElementById('wpq2');
var sub = parentID.getElementsByClassName('subClass');
var lastChild = sub[0].lastChild;
lastChild.style.display = 'none';
Using javascript no idea how to do
Please suggest
Try this instead:
var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get all the a elements
var subs = innerDiv.getElementsByClassName('subClass');
//This will hide all matching elements except the first one
for(var i = 1; i < subs.length; i++){
var a = subs[i];
a.style.display = 'none';
}
Here is a working example
EDIT: The above will only hide the a element, as your text elements are not contained within specific elements then it becomes more tricky. If you are happy to effectively "delete" the HTML you don't want then you can do the following:
var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get the HTML for the a element to keep
var a = innerDiv.getElementsByClassName('subClass')[0].outerHTML;
//replace the HTML contents of the inner DIV with the element to keep
innerDiv.innerHTML = a;
Here is an example
insert new html if you don't need the rest
document.getElementById('wpq2').innerHTML = '<a id="linkTO" class="subClass">New Item</a>';
var parentID = document.getElementById('wpq2');
var innerDiv = parentID.getElementsByClassName('subClass')[0];
var subs = innerDiv.getElementsByClassName('subClass');
subs.forEach(function (sub) { sub.style.display = 'none'; });
document.getElementById("linkTO").style.display = 'block';

Categories