Can't put search results into Hyperlinks and append to a div - javascript

okay i have come across a simple javascript code that will search all the hyperlinks in a page which works briliantly fast. the only problem is that the browser freezes when it tries to remake these links in a div, no error just as soon as i push the button the browser refuses to load. as you can see it gets the input from a form then searches every hyperlink for these terms then is supposed to populate a div with links but it doesn't. the code is as follows.
function search0(){
var lists = document.getElementsByTagName("a");
for (var i = 0; i < lists.length; i++) {
var output = lists[i];
var team1 = document.getElementById("search1").value;
var matchPos1 = output.innerHTML.search(team1);
if(matchPos1 != -1){
var team2 = document.getElementById("search2").value;
var matchPos2 = output.innerHTML.search(team2);
if(matchPos2 != -1){
var elem1 = document.createElement("a")
var styleattr=document.createAttribute("href");
styleattr.nodeValue=output;
elem1.setAttributeNode(styleattr);
var text1 = document.createTextNode(output.innerhtml);
elem1.appendChild(text1);
var parentdiv = document.getElementById("frame2");
parentdiv.appendChild(elem1);
}
}
}
}

You are creating an infinite loop.
The nodeList you create with document.getElementsByTagName("a") is live i.e. if you add a link to the page it will appear in this list automatically! Yes, that's right, even without requerying. Here's a reference doc.
You are adding links to the nodeList which are then matched and added to the end on the nodeList which are then matched and so on and so on
To do what you want to do you should create an initial array of links like this.
//creates a real js array from a nodelist
var list = Array.prototype.slice.call( document.getElementsByTagName("a"), 0 );
Here is an explanation of Array.prototype.slice.call

Also change case-sensitive mistake:
var text1 = document.createTextNode(output.innerhtml);
To
var text1 = document.createTextNode(output.innerHTML);

Related

javascript parse text from <a href> links

Lets say I have
ThisTextChanges
ThisTextChanges
ThisTextChanges
ThisTextChanges
I want to iterate through these and get the "ThisTextChanges" which are some numbers that changes, most accurately timers.
How can i achieve that? jquery is fine.
They are inside a div with id "main_container".
I need to put the text in a var so the href is importanto to know which var i use for each one.
Lets break the task down into several steps:
Get a handle to all of our links (document.querySelectorAll)
learn how to get the current text of an a tag (childNode[0].nodeValue)
put it all together (Array.from, Array.map)
Get a handle to all of our links:
we will use document.querySelectorAll to get list of all nodes that match our selector. here I'm just going to use the selector a, but you probably have a class that specifies these links vs other links on the page:
var links = document.querySelectorAll('a');
Get the text of a link
This one is a bit more complicated. There are several ways to do this, but one of the more efficient ways is to loop through the child nodes (which will mostly be text nodes), and append the node.nodeValue for each one. We could probably get away with just using the nodeValue of the first child, but instead we'll build a function to loop through and append each.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
Put it all together
To put it all together we will use Array.map to turn each link in our list into the text inside it. This will leave us with an array of strings. However in order to be able to pass it to Array.map we will have to have an array, and document.querySelectorAll returns a NodeList instead. So to convert it over we will use Array.from to turn our NodeList into an array.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
var linkTexts = Array.from(document.querySelectorAll('a'))
.map(getText);
console.log(linkTexts);
this is text
this is some more text
You can just add condition in the a selector as follows:
var array = [];
$('#main_container a[href="/example2"]').each(function(){
array.push($(this).html());
});
console.log(array);
You can iterate and store them in an Array
var arr = [];
$("a").each(function(){
arr.push($(this).text());
console.log( arr );
});
you can achieve that in may ways. this example using for loop.
var main_container = document.getElementById("main_container");
var items = main_container.getElementsByTagName("a");
for (var i = 0; i < items.length; ++i) {
// do something.....
}
var array = [];
$('#main_container a').each(function(){
array.push($(this).html());
});
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_container">
ThisTextChanges 1
ThisTextChanges 2
ThisTextChanges 3
ThisTextChanges 4
</div>
Please try:
$('#main_container > a[href]').each(function() {
var tes = $(this).attr('href').substring(1);
window[tes] = $(this).text();
});
123 will produce var named example1 with value 123, and so on.

Dexie.js iterating a dynamic list

I am using dexie.js, which is an indexDB wrapper. Anywhoo, I have an array that is called from the user's local storage, and my function is supposed to iterate through every list item in the DB and show it. However, upon clicking on my Butane it only shows the most recent input of name.
Note: You can see the entire database by adding a few values in and checking your local storage.
My JsFiddle:
https://jsfiddle.net/enzp3zws/1/
my html:
<ul id="mane"></ul>
my js:
var db = new Dexie("TestDatabase");
db.version(1).stores({
friends: '++id, name, age'
});
var collection = db.friends;
var placement = document.getElementById('rainman');
var jacement = document.getElementById('rainboy');
var stacement = document.getElementById('mane');
var listed = document.createElement('li');
function addrain(){
collection.each(function(friend){
var element = [friend.name];
for (var i = 0; i < element.length; i++){
listed.textContent = element[i];
document.getElementById('mane').appendChild(listed);
//alert(element); <-- this call alerts all names in database.
}
});
}
Please excuse the randomness of some of these variable names. I don't know what sleep is anymore.
You need to create a new 'li' element each time:
//Remove var listed = ... line in header, then:
function addrain(){
collection.each(function(friend){
var element = [friend.name];
for (var i = 0; i < element.length; i++){
var listed = document.createElement('li');
listed.textContent = element[i];
document.getElementById('mane').appendChild(listed);
}
//alert(element); <-- this call alerts all names in database.
});
}
The reason your code did not work before is that you only created one li element, and repeatedly changed its text and re-inserted it at different locations.

Find and list all URL-s as clickable links to the bottom of the page

I'm trying to write a javascript what is searching for all of the links on the page, then it is adding them to the bottom, under the original content.
"Document.links" seems to do the finding part, it is also listing them, but they are not clickable. So I tried to add some html codes (startHref and endHref lines), which broke the whole thing of course.
My (non-working) script:
var links = document.links;
for(var i = 0; i < links.length; i++) {
var preLink = document.createTextNode("LINK: ");
var linkHref = document.createTextNode(links[i].href);
var lineBreak = document.createElement("br");
var startHref = document.createElement("a href="");
var endHref = document.createElement(""");
document.body.appendChild(preLink);
document.body.appendChild(startHref);
document.body.appendChild(linkHref);
document.body.appendChild(endHref);
document.body.appendChild(lineBreak);
}
If this will work I'd also like to have them listed with a number in front of each line (starting with 1 - could be set in the preLink part) - if not too hard to implement.
Also, is there a way to list not all of the links, but only those matching with something? Like only links with a specific domain. Thank you!
As you have already found out, you can get all links in a document with:
var links = document.links;
Now you have an HTMLCollection. You can iterate through it and display all links. For better layout you can put them in a paragraph (p). This would be the loop:
for (var i = 0; i < links.length; i++) {
var p = document.createElement("p");
p.appendChild(links[i]);
document.body.appendChild(p);
}
Now all links are appended at the end of the page, every link is on its own line and they are clickable. Please try this out.
EDIT: as of your comment, if I understand it right, you have just to put one additional line:
for (var i = 0; i < links.length; i++) {
var p = document.createElement("p");
// the following line is added
links[i].innerHTML = links[i].href;
p.appendChild(links[i]);
document.body.appendChild(p);
}
That line will simply replace the inner HTML of the link with its value for the attribute href.
EDIT:
The variable links just points to document.links. The existing links are therefore removed from their original position and appended to the end. If you try to create new links in the for loop, like document.createElement("a") you will create an endless loop, because you're iterating through all links in the document. You remember, the variable links is not a snapshot of document.links when created, but points to it.
You can work around this with creating an array:
var links = [];
// populate the array links
for (var j = 0; j < document.links.length; j++) {
links.push(document.links[j].cloneNode());
}
Now this is a snapshot of all links on the page. Every links is cloned and pushed to the array. Now run the for loop and the original links aren't removed.
If the original link was something like:
This is an example.
it will become:
http://example.com
But if you want just:
http://example.com
then you have to adapt the code:
for (var i = 0; i < links.length; i++) {
var p = document.createElement("p");
var a = document.createElement("a");
a.href = links[i].href;
a.text = links[i].href; // you can use text instead of innerHTML
p.appendChild(a);
document.body.appendChild(p);
}
If you want to style the output you can add classes like this:
p.classList.add("my-css-class");
I hope this helps you to achieve your goal.

How to split a comma separated string from user input

I want to be able to have the user list things in an input box (comes up via an alert) and then once submitted have those options replace the default text in the string. They need to be separated after each comma as well and with each thing listed, the loop should paste the text into it when it runs, and repeat with the rest in the list.
Is this possible?
This is what I'm working on right now: http://jsbin.com/nivah/1 and it'll only allow you to type in one thing. Because if you type in several options with commas it includes the commas and all the options in the link which obviously won't return anything.
Here's my javascript code.
var link0='http://www.twitter.com/';
var user=['bob', 'joe', 'tony'];
var user = prompt("I want to message:", user);
var link3=".tumblr.com";
var iframe = document.getElementById("username");
var opt = (link0 + user + link3);
var el = document.createElement("iframe");
for(var i = 0; i < user.length; i++) {
el.setAttribute("src", opt);
iframe.appendChild(el);
}
var array = user.split(',');
Anyone know what I am doing wrong?
I had it working before to repeat the loop based on what i submitted but it was doing it by make each letter of the word its own link in the iframes. Which is not what I want, but as close as I've ever gotten to the loop interaction with the user inputted text.
You need to use the split() but at the right place in your code. Also, your logic is not going to work, You need to create each iframe within the for loop, something like this -
WORKING DEMO - http://jsbin.com/ciquvatu/1/edit
var link0='http://www.tumblr.com/ask_form/';
var user = ['killthemwithyourawesome', 'barrowman-ilove', 'down-with-these-ships'];
var user = prompt("I want to message:", user);
var link3=".tumblr.com";
var array = user.split(',');
for(var i = 0; i < array.length; i++) {
var iframe = document.getElementById("username");
var opt = (link0 + array[i] + link3);
var el = document.createElement("iframe");
el.setAttribute("src", opt);
iframe.appendChild(el);
}
This should do what you are looking for.

javascript - get all anchor tags and compare them to an array

I have been trying forever but it is just not working, how can I check the array of urls I got (document.getElementsByTagName('a').href;) to see if any of the websites are in another array?
getElementByTagName gives you a nodelist (an array of nodes).
var a = document.getElementsByTagName('a');
for (var idx= 0; idx < a.length; ++idx){
console.log(a[idx].href);
}
I really suggest that you use a frame work for this, like jquery. It makes your life so much easier.
Example with jquery:
$("a").each(function(){
console.log(this.href);
});
var linkcheck = (function(){
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]===obj){
return i;
}
}
return -1;
}
}
var url_pages = [], anchor_nodes = []; // this is where you put the resulting urls
var anchors = document.links; // your anchor collection
var i = anchors.length;
while (i--){
var a = anchors[i];
anchor_nodes.push(a); // push the node object in case that needs to change
url_pages.push(a.href); // push the href attribute to the array of hrefs
}
return {
urlsOnPage: url_pages,
anchorTags: anchor_nodes,
checkDuplicateUrls: function(url_list){
var duplicates = []; // instantiate a blank array
var j = url_list.length;
while(j--){
var x = url_list[j];
if (url_pages.indexOf(x) > -1){ // check the index of each item in the array.
duplicates.push(x); // add it to the list of duplicate urls
}
}
return duplicates; // return the list of duplicates.
},
getAnchorsForUrl: function(url){
return anchor_nodes[url_pages.indexOf(url)];
}
}
})()
// to use it:
var result = linkcheck.checkDuplicateUrls(your_array_of_urls);
This is a fairly straight forward implementation of a pure JavaScript method for achieving what I believe the spec calls for. This also uses closures to give you access to the result set at any time, in case your list of urls changes over time and the new list needs to be checked. I also added the resulting anchor tags as an array, since we are iterating them anyway, so you can change their properties on the fly. And since it might be useful to have there is a convenience method for getting the anchor tag by passing the url (first one in the result set). Per the comments below, included snippet to create indexOf for IE8 and switched document.getElementsByTagName to document.links to get dynamic list of objects.
Using Jquery u can do some thing like this-
$('a').each(function(){
if( urls.indexOf(this.href) !- -1 )
alert('match found - ' + this.href );
})
urls is the your existing array you need to compare with.

Categories

Resources