Create links inside a list - javascript

I have a list looking like this
<li class="list">text1</li>
<li class="list">text2</li>
<li class="list">text3</li>
and want to make the text to links, with this result using JavaScript
<li class="list>text1</li>
<li class="list>text1</li>
<li class="list>text1</li>
I already did this, but don't know how to do next?
var link1 = document.createElement("a");
link.href = "#text1"
Is it possible to make a loop or something similar, so that I don't have to write the same code for all three links?

Yes, first you need to find all of the list class tags and loop through them.
var lists = document.getElementsByClassName("list");
for(var i=0; i<lists.length; i++) {
Next find the text of the current list element, store it in a variable and then clear the element's text.
var text = lists[i].textContent;
lists[i].textContent = "";
Third, create the a element and make the textContent of the a element the text of the current list and the href, the current text plus the # sign.
var a = document.createElement("a");
a.href = "#"+text;
a.textContent = text;
And finally append the a to the current list element.
lists[i].appendChild(a);
var lists = document.getElementsByClassName("list");
for(var i=0; i<lists.length; i++) {
var text = lists[i].textContent;
lists[i].textContent = "";
var a = document.createElement("a");
a.href = "#"+text;
a.textContent = text;
lists[i].appendChild(a);
}
<li class="list">text1</li>
<li class="list">text2</li>
<li class="list">text3</li>
`

Iterate over the list elements adding the anchor HTML as a text replacement:
[].forEach.call(document.querySelectorAll('.list'), function (el) {
var txt = el.textContent;
el.innerHTML = '' + txt + '';
});
DEMO

Related

Trying to sort a list in my html with javascript

im having a bit of trouble with the code below:
Html:
<p>click to <a onclick ="sortList(); return false;" href="#">sort</a></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
Javascript:
function sortList(listId) {
var list = document.getElementbyId(listId);
var children = list.childNodes;
var listItemsHTML = new Array();
for (var i = 0; i < children.length; i++) {
if (children[i].nodeName === "LI") {
listItemsHTML.push(children[i].innerHTML);
}
}
listItemsHTML.sort();
list.innerHTML="";
for (var i = 0; i < listItemsHTML.length; i++) {
list.innerHTML += "<li>" + listItemsHTML[i] + "</li>";
}
}
however, when i try and click the link to sort the html does nothing and im not sure what the problem is. i am referencing and was able to use changeit and echo function to produce an alert message in the .js file just cant sort
You need to pass the listId to the function as an argument like onclick ="sortList('fruits'); return false;" and change document.getElementbyId() to document.getElementById() which is a typo
function sortList(listId) {
var list = document.getElementById(listId);
var children = list.childNodes;
var listItemsHTML = new Array();
for (var i = 0; i < children.length; i++) {
if (children[i].nodeName === "LI") {
listItemsHTML.push(children[i].innerHTML);
}
}
console.log(listItemsHTML);
listItemsHTML.sort();
list.innerHTML="";
for (var i = 0; i < listItemsHTML.length; i++) {
list.innerHTML += "<li>" + listItemsHTML[i] + "</li>";
}
}
<p>click to <a onclick ="sortList('fruits'); return false;" href="#">sort</a></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
Firstly, it's document.getElementById ... capital B in ById
Secondly, use list.children rather than list.childNodes - don't need to care about text nodes
Thirdly, use list.appendChild on a sorted list to move the existing nodes, rather than mucking around with innerHTML
function sortList(listId) {
var list = document.getElementById(listId);
Array.from(list.children).sort((a, b) => a.textContent > b.textContent).forEach(li => list.appendChild(li));
}
Or, if you're not comfortable with ES2015+
function sortList(listId) {
var list = document.getElementById(listId);
Array.from(list.children).sort(function (a, b) {
return a.textContent > b.textContent;
}).forEach(function (li) {
return list.appendChild(li);
});
}
and finally, change
<a onclick ="sortList(); return false;" href="#">
to
<a onclick ="sortList('fruits'); return false;" href="#">
I know its already answered, but of thought of providing little different version.
Use buttons instead of <a>, Using 'href='#' is not a good practice.
Never create a element from string. Always use document.createElement. Its better!
Write a separate listener for triggering functions. Don't write in HTML itself. It will be harder to manage once application grows.
HTML
<p>click to <button class="sort">sort</button></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
JavaScript
<script type="text/javascript">
function sortList() {
var fruitCollection = [],
fruitsDOM = document.querySelector('#fruits'),
fruitsLists = document.querySelectorAll('li');
fruitsLists.forEach(function(item) {
fruitCollection.push(item.textContent);
});
fruitCollection.sort();
fruitsDOM.innerHTML = null;
fruitCollection.forEach(function(item) {
var newNode = document.createElement('li');
newNode.textContent = item;
fruitsDOM.appendChild(newNode);
});
}
document.querySelector('.sort').addEventListener('click', sortList);
</script>

How can I generate a list of modified hyperlinks based on user input

I'm trying to modify a list of URLs using either HTML or Javascript. I collected a list of sites that will embed any YouTube video. They look like this:
http://music-dump.com/id/00000
http://youtube-id.com/download/00000
etc.
I want to generate a list of new hyperlinks with the "00000" replaced with the userInput. The list should generate from a button click or on-the-fly user typing. So far I found this:
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "http://music-dump.com/id/" + userInput;
lnk.innerHTML = lnk.href;
}
</script>
Type the youtube code and click Open! <a href="" id=lnk>link</a> <br>
<input type='text' id='userInput' value='' />
<input type='submit' onclick='changeText2()' value='Open'/>
But this will only generate one link. I want a huge list. Is it possible?
Is this what you want?
Type the youtube code and click Open!
<div id="links">
</div>
<input type='text' id='userInput' value='' />
<input type='submit' onclick='changeText2()' value='Open'/>
And the javascript:
var links = [
"http://music-dump.com/id/00000",
"http://youtube-id.com/download/00000",
"http://example.com/v/00000"
];
function changeText2() {
var userInput = document.getElementById('userInput').value;
links.forEach(function(link) {
link = link.replace("00000", userInput);
var a = document.createElement("a");
a.href = link;
a.innerHTML = link;
document.getElementById('links').appendChild(a);
});
}
http://jsfiddle.net/u7hfuagw/2/
You need to keep track of your links in a list (hardcoded in your javascript file or retrieved from a service via XHR request for example). Then, for each link, insert a <a> tag in the DOM. Once the links are inserted, you only need to listen to the value of the input to update the href values ;)
HTML file:
<input type="text" id="userInput" placeholder="Start typing an ID...">
<ul id="links"></ul>
JS file:
(function () {
'use strict';
// the "huge" list of links
var linksCollection = [
'http://music-dump.com/id/{id}',
'http://youtube-id.com/download/{id}'
];
init();
function init() {
var li, a;
// for each link in the collection, we are going to create
// a <a> element within a <li> element
for (var i = 0; i < linksCollection.length; i++) {
li = document.createElement('li');
a = document.createElement('a');
a.href = linksCollection[i].replace('{id}', 0);
a.innerHTML = a.href;
li.appendChild(a);
document
.getElementById('links')
.appendChild(li);
}
document
.getElementById('userInput')
.addEventListener('keyup', handleInput);
}
function handleInput() {
var inputElement = document.getElementById('userInput');
var links = document.getElementById('links').childNodes;
var aElement;
for (var i = 0; i < links.length; i++) {
aElement = links[i].getElementsByTagName('a')[0];
aElement.href = linksCollection[i].replace('{id}', inputElement.value);
aElement.innerHTML = aElement.href;
}
}
})();
Link to the plunker: http://plnkr.co/edit/C1b6ccnpFrnNhDAsqxTF
PS: in the source code above, <a> are placed in a <li> tag for a better visual rendering. Feel free to place the <a> in other tags or to add class names for the styling. For example:
li = document.createElement('li');
li.className = 'list-item';

Taking tab example from fiddle ans use in my project

http://jsfiddle.net/738wtmhs/1/
using above example in fiddle in my own project: for the purpose of this exercise I am using DOM methods to create and append the elements.
function GetFeatureProperties(feature) {
//add header to 1st FirstTabContent
var featureHeader = "<center><b> <FONT COLOR='FF6600'> Feature Properties </FONT> </b> </center> </br>";
var FirstTabContent = document.createElement('div');
FirstTabContent.id = "tabs-1";
FirstTabContent.innerHTML = featureHeader;
//Second Tab
var SecondTabContent = document.createElement('div');
SecondTabContent.id = "tabs-2";
var newImage = document.createElement("img");
newImage.src = "http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg";
newImage.width = "100";
newImage.height = "100";
SecondTabContent.appendChild(newImage);
//add li and ul
var DivHolding2Tabs = document.createElement('div');
DivHolding2Tabs.class = "shoptab";
var header2 = document.createElement('h2');
header2.innerHTML = "Feature";
DivHolding2Tabs.appendChild(header2);
var _ul = document.createElement('ul');
var _anchor1 = document.createElement("a");
_anchor1.href = "#tabs-1";
_anchor1.innerHTML = "Info";
var _li1 = document.createElement('li');
_li1.appendChild(_anchor1);
var _anchor2 = document.createElement("a");
_anchor2.href = "#tabs-2";
_anchor2.innerHTML = "Images";
var _li2 = document.createElement('li');
_li2.appendChild(_anchor2);
_ul.appendChild(_li1);
_ul.appendChild(_li2);
DivHolding2Tabs.appendChild(_ul);
DivHolding2Tabs.appendChild(FirstTabContent);
DivHolding2Tabs.appendChild(SecondTabContent);
var jelm = $(DivHolding2Tabs); //convert to jQuery Element
var htmlElm = jelm[0]; //convert to HTML Element
var OuterDiv = document.createElement('div');
OuterDiv.id = "loc-list";
OuterDiv.appendChild(htmlElm);
return OuterDiv.innerHTML;
}
and this looks like the image seen below....if I click on the link 'image' the page jumps a bit but nothing happens and nothing happens when I press 'info' also I have included the CSS in my project so why arnt the tabs showing and yes I am using jquery ui 1.10.3.custom.js
---------------------------------------------------------------------------------------------
UPDATE
<ul id="list"><li><div><h2>Feature</h2><ul><li>Info</li><li>Images</li></ul><div id="tabs-1"><center><b> <font color="FF6600"> Feature Properties </font> </b> </center> <br></div><div id="tabs-2"><img src="http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg" width="100" height="100"></div></div></li></ul>
Also changed from jquery 1.10.3 custom to jquery 1.11.2.custom with all the downloaded tabs selected
If you look at this fiddle, I managed to make it work.
Here's the possible problems
1) I changed return OuterDiv.innerHTML because I needed the <div id="loc-list"> to be part of the code to initialize it. You gave it an id so my guess is you wanted it to be included but by doing innerHTML, you didn't get it.
2) Once your function returns, you need to initialize the tabs with $('#loc-list').tabs();

Append element in tag right before contents with Javascript

I'll illustrate with an example: I need to convert the following html with javascript
<a>Text 1</a>
<a>Text 2</a>
<a>Text 3</a>
...
to code
<a><input/>Text 1</a>
<a><input/>Text 2</a>
<a><input/>Text 3</a>
...
I don't have a clue how to achieve that with createElement, appendChild or insertBefore/After.
It's not that hard :)
​(function() {
var links = document.getElementsByTagName("a"),
input,
i = links.length;
while (i--) {
input = document.createElement("input");
links[i].insertBefore(input, links[i].firstChild);
}
}())​
.insertBefore, and .firstChild
You could insert your new input element before the first child of each anchor:
// Gather up a reference to all anchors
var anchors = document.getElementsByTagName("a"), inputEl;
// Cycle over all of them
for ( var i = 0; i < anchors.length; i++ ) {
// Create a new input field
inputEl = document.createElement("input");
// Insert it before the first child of the anchor
anchors[i].insertBefore( inputEl, anchors[i].firstChild );
}
Demo: http://jsbin.com/ibugul/edit#javascript,html
Regular Expression
Or you could use the replace method:
var a = document.getElementsByTagName("a"),
c = a.length;
while ( c-- ) {
a[c].innerHTML = a[c].innerHTML.replace( /(.*)/, function( s, c2 ){
return "<input />" + c2;
});
}
Modify .innerHTML
var a = document.getElementsByTagName("a"),
c = a.length;
while ( c-- ) a[c].innerHTML = "<input />" + a[c].innerHTML;
jQuery
If you're already using jQuery on your site, you could use that to make this even shorter:
$("a").prepend("<input />");
Note, it is not worth including the library just for this.

Regular expression in javascript to get contents of <span> tags

I have a string with this form
<p>Central: <span class="fieldText">Central_Local</span>
<br>Area Resolutoria: <span class="fieldText">Area_Resolutoria</span>
<br>VPI: <span class="fieldText">VIP</span>
I'm trying to get the span elements, and find the values within
var message = currentMarker.get("mensaje");
var pat = new RegExp("^(.*?<span .*?>(.*?)</span>.*?)+$");
message.match(pat);
I need to get these values:
Central_Local
Area_Resolutoria
VIP
IP_ERX
How can this be done, or how can my regex be improved?
jQuery
var message = currentMarker.get("mensaje");
var contents = [];
$('<div>', {html: message }).find('span.fieldText').each(function(){
contents.push( $(this).text() );
});
demo at http://jsfiddle.net/DfDPR/2/
Pure javascript
var message = currentMarker.get("mensaje");
var contents = [];
var div = document.createElement('div');
div.innerHTML = message;
var spans = div.getElementsByTagName('span');
for (var span = 0; span < spans.length; span++)
{
contents.push(spans[span].innerHTML);
}
demo at http://jsfiddle.net/DfDPR/3/
As mentioned in the comments, regex is not a good candidate for parsing HTML...
Trivial task in jQuery:
var values = $('span.fieldText', message).map(function(){
return $(this).text();
}).get();
values will be an array with all the values you need. You can iterate over it or do anything you like.

Categories

Resources