Javascript - how do I iterate thru all URLs of a given page - javascript

I am not experienced in Javascript. After the page finishes loading, I need to iterate thru all URLs a given page and perform some cleanings.
How do I do that?
Something like
for i = 0 to (number of URLS on the page) {
doSomething (URL(i));
}
thanks

If you want to link through all anchors, use document.links, like this:
for(var i = 0, l=document.links.length; i<l; i++) {
doSomething(document.links[i].href);
}
This is a collection already maintained by the browser (for prefetching under the covers mostly, but other reasons as well)...no need for a document.getElementsByTagName() here. Note: this also gets <area> elements, as long as they have a href attribute...also a valid form of navigation.

I'd always recommend having jQuery around for times like this as it makes it far easier.
For example on page load:
$(document).ready(function(){
$('a').each(function(index) {
alert(index + ': ' + $(this).text());
});
});

Use this function:
var anchors = document.getElementsByTagName("a");
for (anchor in anchors){
doSomething(anchor):
}

Or just plain Javascript with a bit of readability:
var myURL = document.getElementsByTagName('a');
for(var i=0; i<myURL.length; i++)
console.log(myURL[i].getAttribute('href'));

Related

Convert jquery to javascript for localstorage

I am trying to convert a small jquery script to pure javascript. Whats the best way to go about it? I keep getting "$(this) is not defined" error.
var lastTab = localStorage.getItem('lastTab');
if (lastTab) {
$('a[href="'+lastTab+'"]').click();
}
You can convert the snippet to plain JS easily. But keep in mind, that this will not work, if the click event listener is registered with jQuery, because you can't trigger event listeners created with jQuery on vanilla JS. The reason is, that jQuery uses an own implementation of events.
For converting your snippet you will need querySelectorAll, to select all elements by it's href, and then loop the found elements to execute click.
var lastTab = localStorage.getItem('lastTab');
if( lastTab ) {
// get all elements by href
var elements = document.querySelectorAll("a[href='" + lastTab + "']");
// loop all elements because it could be more than one found
for( var i = 0, l = elements.length; i < l; i++ ) {
elements[i].click();
}
}
Fully working example.
(posted on jsfiddle, because SO don't allow usage of localStorage)

Get index of class clicked in JavaScript. No jQuery

Edit:
The suggestion points to a jquery answer, which I would prefer not to use. I may have done a bad job explaining this. When you click on a class, I want to know which one it is of all the classes sharing that same name. For instance, if there are 8 buttons on the page with a classname of 'mybutton', when I click on one, I want to know which index it was ex: mybutton[3].
Original Post:
Is there a simple way to get the index of the class you clicked? I can't seem to find anything in the MouseEvent obj. I have searched stackoverflow/internet but what I can find seems to be over complicated,unanswered, or using jQuery. Example:
document.body.addEventListener('click',function(event){
console.log(event.target.className);
console.log(event.target.className.index??)`
});
I feel like it should be simple, no?
There's no "easy" way to do it; that is, the DOM API doesn't directly answer that sort of question. You can however simply search through the list of elements that match any characteristic you want and see which one your element matches:
function indexIn(selector, element) {
var list = document.querySelectorAll(selector);
for (var i = 0; i < selector.length; ++i)
if (list[i] === element) return i;
return -1;
}
Then your handler can look through the .classList on the clicked element:
document.body.addEventListener('click',function(event){
for (var i = 0; i < this.classList; ++i)
console.log("index for class " + this.classList[i] + ": " +
indexIn("." + this.classList[i], this));
});

Use JavaScript to find a specific link

Could anyone help me with a function for JavaScript which searches the source code and compares all of the links on the site with the specific link I am looking for.
For example: I am executing the JavaScript on www.youtube.com and I am looking for one specific YouTube link.
It could look like this (which of course doesn't work):
if(document.body.indexOf("http://www.youtube.com/SPECIFICURL")!== -1){
console.log("Url found");
}else{
console.log("Url not found");
}
How can I accomplish this?
Try querySelectorAll() with CSS3 selectors:
document.querySelectorAll('a[href*="http://www.youtube.com/SPECIFICURL"]')
Fiddle
This selector says find all links with an href attribute that contains a specific string. Lets break this down a little bit:
a - this is the element type, e.g. "link"
href - this is the element attribute
*= - this essentially means contains. There are different type of equality checks that can be used: starts with, contains word, ends with, etc. The jQuery selectors documentation is quite good.
"..." - everything in quotes after the equal sign is the substring the query is looking for.
function find_link_by_href(address)
links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++) {
if( links[i].href === address ) {
console.log("Url found");
return;
}
}
You can call it like this:
find_link_by_href("http://www.youtube.com/SPECIFICURL");
Use Array.prototype.some to see if at least one element in document.links has the href you're looking for.
var has_link = [].some.call(document.links, function(link) {
return link.href === 'http://www.youtube.com/SPECIFICURL';
});
You can patch it in old browsers using the patch found at MDN Array#some
You can use document.links to get the anchors, then just loop through grabbing the href, like this:
var arr = [], l = document.links;
for(var i=0; i<l.length; i++) {
arr.push(l[i].href);
}
//arr is now an array of all the href attributes from the anchors in the page
See here.
Then loop through the array to check for your specific link.

Count all <a> on html page

I want to get all the <a> tags from an Html page with this JavaScript method:
function() {
var links = document.getElementsByTagName('a');
var i=0;
for (var link in links){i++;}
return i;
}
And i noticed it's won't return the correct number of a tags.
Any idea what can by the problem?
Any idea if there is any other way to get all the href in an Html ?
Edit
I tried this method on this html : http://mp3skull.com/mp3/nirvana.html .
And i get this result:"1". but there are more results in the page.
You don't need a loop here. You can read length property.
function getACount() {
return document.getElementsByTagName('a').length;
}
You don't have to loop over all of them just to count them. HTMLCollections (the type of Object that is returned by getElementsByTagName has a .length property:
$countAnchors = function () {
return document.getElementsByTagName('a').length;
}
Using getElementsByTagName("a") will return all anchor tags, not only the anchor tags that are links. An anchor tags needs a value for the href property to be a link.
You might be better off with the links property, that returns the links in the page:
var linkCount = document.links.length;
Note that this also includes area tags that has a href attribute, but I assume that you don't have any of those.
UPDATE Also gets href
You could do this
var linkCount = document.body.querySelectorAll('a').length,
hrefs= document.body.querySelectorAll('a[href]');
EDIT See the comment below, thanks to ttepasse
I would cast them to an array which you then slice up, etc.
var array = [];
var links = document.getElementsByTagName("a");
for(var i=0; i<links.length; i++) {
array.push(links[i].href);
}
var hrefs = array.length;
The JavaScript code in the question works as such or, rather, could be used to create a working solution (it’s now just an anonymous function declaration). It could be replaced by simpler code that just uses document.getElementsByTagName('a').length as others have remarked.
The problem however is how you use it: where it is placed, and when it is executed. If you run the code at a point where only one a element has been parsed, the result is 1. It needs to be executed when all a elements have been parsed. A simple way to ensure this is to put the code at the end of the document body. I tested by taking a local copy of the page mentioned and added the following right before the other script elements at the end of document body:
<script>
var f = function() {
var links = document.getElementsByTagName('a');
var i=0;
for (var link in links){i++;}
return i;
};
alert('a elements: ' + f());
</script>
The results are not consistent, even on repeated load of the page on the same browser, but this is probably caused by some dynamics on the page, making the number of a elements actually vary.
What you forget here was the length property. I think that code would be:
var count = 0;
for (var i = 0; i < links.length; i++) {
count++;
}
return count;
Or it would be:
for each (var link in links) {
i++;
}
length is used to determine or count the total number of the element which are the result.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for (For Loop)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in (Foreach Loop)

How to dynamically remove a stylesheet from the current page

Is there a way to dynamically remove the current stylesheet from the page?
For example, if a page contains:
<link rel="stylesheet" type="text/css" href="http://..." />
...is there a way to later disable it with JavaScript? Extra points for using jQuery.
Well, assuming you can target it with jQuery it should be just as simple as calling remove() on the element:
$('link[rel=stylesheet]').remove();
That will remove all external stylesheets on the page. If you know part of the url then you can remove just the one you're looking for:
$('link[rel=stylesheet][href~="foo.com"]').remove();
And in Javascript
this is an example of remove all with query selector and foreach array
Array.prototype.forEach.call(document.querySelectorAll('link[rel=stylesheet]'), function(element){
try{
element.parentNode.removeChild(element);
}catch(err){}
});
//or this is similar
var elements = document.querySelectorAll('link[rel=stylesheet]');
for(var i=0;i<elements.length;i++){
elements[i].parentNode.removeChild(elements[i]);
}
If you know the ID of the stylesheet, use the following. Any other method of getting the stylesheet works as well, of course. This is straight DOM and doesn't require using any libraries.
var sheet = document.getElementById(styleSheetId);
sheet.disabled = true;
sheet.parentNode.removeChild(sheet);
I found this page whilst looking for a way to remove style sheets using jquery. I thought I'd found the right answer when I read the following
If you know part of the url then you can remove just the one you're looking for:
$('link[rel=stylesheet][href~="foo.com"]').remove();"
I liked this solution because the style sheets I wanted to remove had the same name but were in different folders. However this code did not work so I changed the operator to *= and it works perfectly:
$('link[rel=stylesheet][href*="mystyle"]').remove();
Just thought I'd share this in case it's useful for someone.
This will disable any stylesheet matching the regular expression searchRegEx provided against the URL of each stylesheet.
let searchRegEx = /example.*/;
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].href.search(searchRegEx) != -1) {
document.styleSheets[i].disabled = true;
}
}
Nobody has mentioned removing a specific stylesheet without an ID in plain Javascript:
document.querySelector('link[href$="something.css"]').remove()
("$=" to find at end of href)
This will reset your page's styling, removing all of the style-elements. Also, jQuery isn't required.
Array.prototype.forEach.call(document.querySelectorAll('style,[rel="stylesheet"],[type="text/css"]'), function(element){
try{
element.parentNode.removeChild(element)
}catch(err){}
});
This is for disable all <style> from html
// this disable all style of the website...
var cant = document.styleSheets.length
for(var i=0;i<cant;i++){
document.styleSheets[i].disabled=true;
}
//this is the same disable all stylesheets
Array.prototype.forEach.call(document.styleSheets, function(element){
try{
element.disabled = true;
}catch(err){}
});
To expand on Damien's answer, the test method (which returns true or false) would probably be a better fit than search and is slightly faster. Using this method would yield:
for (var i = 0; i < document.styleSheets.length; i++) {
if (/searchRegex/.test(document.styleSheets[i].href)) {
document.styleSheets[i].disabled = true;
}
}
If you don't care about IE support this can be cleaned up with a for...of loop
for (const styleSheet of document.styleSheets) {
if (/searchRegex/.test(styleSheet)) {
styleSheet.disabled = true;
}
}
Suppose you want to remove a class myCssClass then the most easy way to do it is element.classList.remove("myCssClass");

Categories