I'm on a site where I would like to grab all the href links and click it. I know I could do this. document.getElementById('yourLinkID').click(); how ever, the issue is the href dosen't have an id, only a title. Can I somehow click all the href by it's title?
Accessing the document.links array would be the solution you are looking for.
From there, though, clicking one would cause the page to navigate away to its target, and the script would stop executing. If you must click them all, what you could do is loop through them, and set the target of an iframe with the link's href attribute.
You can use document.querySelectorAll() with selector a[href] to retrieve all <a> elements having href attribute set, or [href] to retrieve all elements having an href attribute set; for..of loop to iterate collection
var hrefs = document.querySelectorAll("a[href]");
for (let elem of hrefs) {
// do stuff
console.log(elem.href);
}
use querySelectorAll:
document.querySelectorAll("[title=foo]")
Which will give you an array.
iterate through the array if your goal is to click all the links.
obviously, clicking a link will redirect you to that page and will pause script execution.
a dirty solution would be to use:
selectedElement.setAttribute('target', '_blank');
where selectedElement is the link's selector.
this makes the url open in a new tab.
No idea why you would want to do this as each <a href... will be activated and after the first one it will be up to the browser to work out what happens.
var aList = document.getElementsByTagName('a');
var i, max = aList.length;
for(i=0;i<max;i++) {
aList[i].click();
}
Hello
world
You can try the following solution,This will loop through each href and Click it.
$('a[href]').each(function ()
{
$(this).trigger('click');
});
Related
I have seen the post How to update (append to) an href in jquery? , but it doesn't seem like the answer can help at my case.
I am currently using a plugin(easytab) to create a few different tab and every tab contains a tag like <a id="tabopen" href="www.text.com/custom/questions/ask/">
<a id="tabopen" href="www.text.com/default/questions/ask/">
and for some reason I have a button which append some extra path to all the href in order to redirect user to the right place.
I have tried to use
$("a#tab1").each(function() {
var _href = $(this).attr("href");
$(this).attr("href", _href + 'startDate=20160121?endDate=20160212');
});
but instead append the 'startDate=20160121?endDate=20160212' it replace everything to www.text.com/custom/questions/ask/startDate=20160121?endDate=20160212 , which is not right, how should i fix it?
Update 1:
I am sorry that i have provide wrong description at, the ids are actually the same in the plugin.
<a id="tabopen" href="www.text.com/custom/questions/ask/">
<a id="tabopen" href="www.text.com/default/questions/ask/">
$("a#tab1") selects a single <a> element having ID as tab1. To change the href attribute of a single element there is no need of each.
var href = $('a#tab1').attr('href') + '?startDate=20160121&endDate=20160212';
$('a#tab1').attr('href', href);
If having multiple elements with same ID, ID should be unique.
To select all the elements whose ID starts with tab, you can use attribute start with selector. I'll suggest to use a unique class on them.
To change the href attribute value of all the matched elements .attr(attributeName, function) with callback function can be used.
$('a[id^="tab"]').attr('href', function(i, oldHref) {
return oldHref + '?startDate=20160121&endDate=20160212';
});
As said by #charlietfl in the comment, the querystring format should be as follow
'?startDate=20160121&endDate=20160212'
^ ^
Update:
Saying again, ID should be unique., you can use class instead of ID for similar purpose elements.
Change the markup to use class
<a class="tabopen" href="www.text.com/custom/questions/ask/">
<a class="tabopen" href="www.text.com/default/questions/ask/">
And then use the selector
$('.tabopen').something...
BAD PRACTICE:
If you can't change the markup(auto-generated markup by some plugin), you can use attribute value selector to select all elements having same ID
$('a[id="tabopen"]').something...
I have this variabele.
var href = $(this).attr('href');
I get the href from a link. Now i have a lot of display none div's on the page. I want to check if the div have the same id. The id that is in the href. Then the div must be show.
How can i make that check?
Concatenate your href variable with a number sign to produce a jQuery ID Selector, and call .show() on your returned object:
$('#' + href).show();
From my understanding you have a bunch of hidden DIVs that you want to show based on the anchor ID. the code below should work however you should not have more than one ID on a page no matter what element it is assigned to. Best practice is to use classes. It would work the same.
// create a click function for the anchor tag
$('a').click(function(){
//grab the id of the selected anchor tag if if has one if not it will be undefined.
// $(this) represents the current anchor tag in the scope of the click function.
var href = $(this).attr('id');
// look for any other element with the same id and set it to show.
$('#'+href).show();
// cancel the anchor page action.
return false;
});
that's True when using JQuery Selector you can Use Exact
$('#' + href + '').show();
So I know that using "a:first" will get the first link of a page. Lets assume we have the following:
<div class="masterclass">
Link 1
Link 2
</div>
<div class="masterclass">
Link 1
Link 2
</div>
Naturally I can use the following code to get the first "a" of the class "masterclass"
$('.masterclass a:first').click(function() {
alert('yayfirstlink');
});
However I do not understand how to get the first link of every "masterclass"
You need to use find() here because your selector will find all the anchor elements with in .masterclass then filter only the very first one. But when you use .find(), it will find all the .masterclass elements first then will find the first anchor element in each of them.
$('.masterclass').find('a:first').click(function() {
alert('yayfirstlink');
});
or if you are sure that the target element will be the first child of its parent then you can use :first-child
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
Try this,
var oFirstAnchor = $(".masterclass a:first-child");
$(".masterclass a:first-child") is what you are looking for.
so:
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
This is how u loop through each of the masterclass and get the first link of it.
i don't know what you want to do with it though so i can only provide this
$(document).ready(function(){
var fields = $('.masterclass a:first-child');
$.each(fields, function(index, val){
alert(index);
});
});
this alerts the current links array index
http://jsfiddle.net/kBd82/6/
I would recommend using the first of type selector for this.
$('.masterclass a:first-of-type')
This way it will always select the first anchor tag in each masterclass div even if you put other things in the div later.
http://api.jquery.com/first-of-type-selector/
I have several anchor tags on a page with the same id of 'hrefCompare'. I need to dynamically set the value of the href attribute on ALL of these a tags.
I am currently trying to do this:
$("#hrefCompare").attr("href", "foobar.com");
However, this only sets the very first anchor tag with that ID. there's 7 more on this page with the same id of 'hrefCompare'. How can I set all of the href values with that ID?
id must be unique, in this case I advice you to use class, which should work flawlessly:
$(".hrefCompare").attr("href", "foobar.com");
<a href="#" class="hrefCompare">a</b>
<a href="#" class="hrefCompare">b</b>
You cannot do this with IDs (they are unique), try using the same css class for all the elements you want (doesn't matter if this class does not exist).
HTML:
text1
text2
Please avoid using # in href attributes (if you care about behaviors). Read this to know why: Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
Then:
For older jQuery versions use .attr(..) otherwise use .prop(..)
$('.hrefCompare').prop('href', 'http://www.foobar.com');
Finally:
1) To assign the same url to every href attribute of an anchor element, do the following:
$('.hrefCompare').map(function(i, v){ return $(this).prop('href', 'http://www.foobar.com'); });
2) To assign different urls to every href attributes of the anchors according to their possitions (like an array - starting from zero -), do the following:
$('.hrefCompare').map(function(i, v){
if(i === 0) url = 'http://www.stackoverflow.com';
if(i === 1) url = 'http://www.foobar.com';
return $(this).prop('href', url);
});
Using this way...
first anchor, position 0: (text1 => if clicked => will redirect to stackoverflow)
second anchor, position 1: (text2 => if clicked => will redirect to foobar)
Ids must be unique in a DOM. try to use a class name and use jquery each function
$('a').each(function(k,v){
$(v).attr('href','mylink');
});
I have a set of DIVs, each contains an image with an empty anchor tag wrapped around it
Image is here
I then have a 'Continue reading' link just before the div closes
Continue reading <span class="meta-nav">→</span>
Is there a way with jQuery that when the page loads, I can that the href location of the continue reading button and apply that the empty anchor wrapped around my image?
Demo: http://jsfiddle.net/2hu66/1/
It is possible, but it is not a good idea. Links created with js are not visible for google crawers. The right way of doing this is creating a real link instead of "#".
Do the things right not interesting ;).
based on your HTML, you can do this:
$(function(){
$('.card-prod').each(function(){ //for each item
var theLink = $('a[href^="?p"]',this).attr('href'); //get the link
$('a.cardclick',this).attr({'href':theLink}); //set to img link
});
})
You can loop through the "continue reading" links and copy their href, perhaps like this:
$("div.card-prod a:contains('Continue reading')").each(function() {
var $this = $(this);
$this.closest("div.card-prod")
.find("a.cardclick")
.attr("href", $this.attr("href"));
});
Updated Demo: http://jsfiddle.net/2hu66/3/
The :contains selector that I used above is not going to be the most efficient way to do it, but it works. If it were my html I'd probably give those "continue reading" anchor elements a common class and select on that. Or you could select the "meta-nav" spans and then take their parent. (Lots of options, really.)
$('.card-prod').each(function() {
var cr = $(this).find('a:last');
$(this).find('.cardclick').attr('href', cr.attr('href'));
});
example Fiddle: http://jsfiddle.net/2hu66/4/