I'm trying to make a simple javascript command that I can run from the console in Chrome. I have a webpage which is filled with links that all follow the same format such as:
Example
This would take it to www.site/e/example.html
I want to be able to randomly pick on of them and follow the link. I've tried doing it using a regex but can't work out how to use it in the console. Any help here would be appreciated!
This is the simple expression I made (just extracts the "e/example" part):
$ <a href="(.+?).html">.+?<\/a>
You can use document.getElementsByTabName and select all a-elements on page. I guess, it is resilient way than regexp.
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
First select all the links with querySelectorAll:
let links = document.querySelectorAll("a");
Then pick a random value, randomIndex returns an Integer between 0 and the array length.
let randomIndex = Math.floor(Math.random() * links.length);
let randomLink = links[randomIndex].href;
randomLink should now contain a randomly chosen link on the webpage.
What you can do is to list all a elements using document.querySelectorAll. You can then loop through them and extract their href property like so:
const links = [...document.querySelectorAll("a")].map(x => x.href);
Then just select a random element from this array:
const link = links[Math.floor(Math.random() * links.length)];
Related
I am trying to cut down and make my code simpler since my original method is not very readable and I get a lot of hard to understand errors for which I have to scan all of the code word by word as it is all one long line.
Lets say the text input was for
In my original code, I wrote :
//Example : You want to know if any of your favorite games were licensed by Nintendo
var tsf = (The value of a textInput in string form)
tsf.toLowerCase()
//Lets say the textinput said "Name your favorite games"
if(tsf.contains('mario') || tsf.contains('pokemon') || tsf.contains('mortal kombat')||etc,etc) {
Alert.alert('At least one of these games was licensed by Nintendo')
}
This works but in the real code there are a lot more "games" and it requires each and every item in the list as it is related to a health project I'm working on.
My 2nd idea was to create an array with all the elements and see if the array contains tsf
nintendoGames = ['mario','pokemon','mortal kombat','zelda','tetris',etc]
if(nintendoGames.contains(tsf)){
Alert.alert('This game was licensed by Nintendo')
}
This also works but only if tsf is a single word. Incase
tsf = 'mario, zelda'
the array method would not work since the array only contains 'mario' and 'zelda' and not the string 'mario, zelda'
I want to be able to scan to see if any part of the string contains any one of the elements in the array and so far, only the first solution works for me. If there is a modification in the .contains() function that works or if there is a certain script I have to write, it would be very useful. I wasn't able to find much online about this.
I am working on React.js with expo to host the app.
First, we convert the string to an array using 'split'.
Since we separate the games in the string with ', ' your code should be like:
tsf.split(', '); // we receive: ['mario','zelda'].
Then we use 'some' method to check if some of the elements in the array we created are in the 'nintedoGames' array.
const tsf = 'mario, zelda';
const nintendoGames = ['mario', 'pokemon', 'mortal kombat', 'zelda', 'tetris'];
const result = tsf.split(', ').some(game => nintendoGames.includes(game.toLowerCase()));
console.log(result)
let nintendoGames = ['mario','pokemon','mortal kombat','zelda','tetris'];
let str = "This is a mario games where you can play the way you like.";
if(nintendoGames.some(n => str.toLowerCase().includes(n.toLowerCase())))
alert("This game was licensed by Nintendo");
This is my first experience with JS, so please forgive the noob question.
I'm trying to make a userscript for a phpBB forum that'll allow me to automatically bookmark every topic I create.
My approach is to add an onclick listener to the submit button.
I'll use the code found in another question:
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
;
}
Before that though I want to find a link to bookmarking the topic in one of the hrefs on the page and store it as a variable.
I know that it will always take the form of
<a href="./viewtopic.php?f=FORUM_NUMBER&t=TOPIC_NUMBER&bookmark=1&hash=HASH"
The final code should look something like (hopefully it's the correct form)
var link = THE LINK EXTRACTED FROM THE MATCHED HREF
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
setTimeout(function(){ window.location.href = 'link'; }, 1000);
}
My issue is I don't know how to approach locating the href that I need and getting the link from it. Haven't found any similar questions about this.
Thanks in advance for any help
Maybe something like this?
var anchors = document.getElementsByTagName('a'); // get all <a> tags
var link = '';
if (anchors) {
// getAttribute(attributeName) gets the value of attributeName (in your case, the value of 'href' attribute
// .map(), .find() and .filter() are available methods for arrays in JS
// .startsWith() is an available method for matching strings in JS.
// You can even experiment with other regex-based string matching methods like .match()
// Use one of the following lines, based on what you require:
// to get the first matching href value
link = anchors.map(anchor => anchor.getAttribute('href')).find(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
// to get all matching href values as an array
link = anchors.map(anchor => anchor.getAttribute('href')).filter(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
}
Since you're not new to coding, check out this documentation if you're new to JS :)
Happy coding!
You can try document.getElementsByTagName("a"); which returns a collection of all the <a></a> loaded in the dom.
Then you can find it in the list and and use .href to get it's href attribute.
I realise this and similar questions / answers exist already. But I've looked at a lot now and just not sure what simple thing I'm doing wrong. I'm just getting to grips with this.
I have the error "Can't find variable: getElementById" I've try changing the order of the script and HTML.
I used this random method which works fine Get random item from JavaScript array Its just applying it to the src...
This video was also helpful https://www.youtube.com/watch?v=pqLS4oyJ8cA
Here is my code: http://jsfiddle.net/udkhpytm/
<div>
<script id="IntroAnimation" type="text/javascript" charset="utf-8" src=""></script>
</div>
<script type="text/javascript">
var my_array = ['FILE1', 'FILE2', 'FILE3'];
var ri = Math.floor(Math.random() * my_array.length); // Random Index position in the array
getElementById("IntroAnimation").src = ri;
</script>
I'm trying to get a random item from the array and place it in the src of my Script by the scripts ID.
getElementById is a method belonging to the document object. It isn't a standalone function. Change:
getElementById("IntroAnimation").src = my_array[ri];
To:
document.getElementById("IntroAnimation").src = my_array[ri];
Note that I've also changed ri to my_array[ri] as otherwise you're passing in the index position as the src rather than the contents of the array at that specific position.
You need to grab that item from the array, all you did was just get a random number based on the array length.
var my_array = ['FILE1', 'FILE2', 'FILE3'];
var ri = Math.floor(Math.random() * my_array.length);
var file = my_array[ri];
Then you need to add document before getElementById:
doucment.getElementById("IntroAnimation").src = file;
I am having issues with getting exactly values with Javascript.
Following is working version of when we have class on single item.
http://jsfiddle.net/rtnNd/
Actually when code block has more items with same class (see this: http://jsfiddle.net/rtnNd/3), it picks up only the first item which use the class name.
My issue is that I would like to pick up only the last item which use the class name. So I used following code:
var item = $('.itemAnchor')[6];
var href = $($('.hidden_elem')[1].innerHTML.replace('<!--', '').replace('-->', '')).find(item).attr('href');
But it doesn't work though. I don't really know why.
The code that may contains items are using same class, class may be use in 2 items, 3 items, or 6th times. That's why, I want to pick up only the last item to extract.
Can you explain, thank you all for reading my question.
"My issue is that I would like to pick up only the last item which use the class name."
OK, so in a general sense you would use the .last() method:
var lastItem = $('.itemAnchor').last();
Except that there are no elements in the DOM with that class because (in your fiddles) they're all commented out. This is also the reason why the code you showed in your question didn't work. The first line:
var item = $('.itemAnchor')[6];
...sets the item variable to undefined. The selector '.itemAnchor' returns no elements, so $('.itemAnchor') is an empty jQuery object and it has no element at index 6.
You need to use the '.itemAnchor' selector on the html that you get after removing the opening and closing comments with your .replace() statements, so:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor').last().attr('href');
Demo: http://jsfiddle.net/rtnNd/4/
EDIT in response to comment:
"How can we pick up the itemElement before that last one."
If you know you always want the second-last item use .slice(-2,-1) instead of .last(), as shown here: http://jsfiddle.net/rtnNd/5/
Or if you know you want whichever one has an href that contains a parameter h= then you can use a selector like '.itemAnchor[href*="h="]' with .find(), in which case you don't need .last() or .slice():
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor[href*="h="]').attr('href');
Demo: http://jsfiddle.net/rtnNd/6/
Note though that this last method using the attribute-contains selector is picking up elements where the href has the text "h=" anywhere, so it works for your case but would also pick up hh=something or math=easy or whatever. You could avoid this and test for just h= as follows:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor')
.filter(function() {
return /(\?|&)h=/.test(this.href);
}).attr('href');
Demo: http://jsfiddle.net/rtnNd/7/
I am stumped and could really use some help with this gallery I've been working on. I used Ivan's '4 lines of jquery gallery' tutorial to get me where I am at currently. Here's his demo which shows exactly how it all works http://workshop.rs/demo/gallery-in-4-lines/
I've hit the point where I would like to include a previous and back button.
As the images are named '1-large.jpg','2-large.jpg','3-large.jpg'... etc I tried using the .slice() to take the first digit then add 1 or minus 1 to it, resulting in the next/previous pic but that didn't work well at all as my javascript skills are lacking and I don't even know if it's the best way to approach it.
My question is - Is using .slice() the way to go or is there a more simpler code I can use on my buttons?
Any help would be much appreciated.
If you just want the first character of a string:
var name = "1-large.jpg";
var i = name[0];
// i is now '1'
but this won't work for i > 9, so using split would be better:
var i = name.split('-')[0];
// i is now '1'
var i = "1023-large.jpg".split('-')[0];
// i is now '1023'
and to convert string to int:
var num = parseInt("23", 10);
// num is now the number 23, not a string