How to get an element by its href in jquery? - javascript

I want to get an element by its href attribute in jquery or javascript. Is that possible?

Yes, you can use jQuery's attribute selector for that.
var linksToGoogle = $('a[href="https://google.com"]');
Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:
var allLinksToGoogle = $('a[href^="https://google.com"]');

If you want to get any element that has part of a URL in their href attribute you could use:
$( 'a[href*="google.com"]' );
This will select all elements with a href that contains google.com, for example:
http://google.com
http://www.google.com
https://www.google.com/#q=How+to+get+element+by+href+in+jquery%3F
As stated by #BalusC in the comments below, it will also match elements that have google.com at any position in the href, like blahgoogle.com.

var myElement = $("a[href='http://www.stackoverflow.com']");
http://api.jquery.com/attribute-equals-selector/

Yes.
$('a[href=\'http://google.com\']')
http://api.jquery.com/attribute-equals-selector/

Related

JavaScript click href without ID

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');
});

Append new path in all the a href URL

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...

How would I get a classes href below it?

<li class="catalog-list-item" data-icon="false">
<a href="/items/170893265">
How would I get the href /items/ and console.log the ID under catalog-list-item?
I tried parentNode and stuff, nothing seems to work for me.
To log the href attribute, I'd do something like this
$(".catalog-list-item a").each(
function(){
console.log($(this).attr("href"));
});
I don't completely catch the idea of logging the ID - there is no ID mentioned in your code example.
By using jQuery selector (jQuery documentation, W3Schools), you can retrieve all anchor tags that are children of an element with the '.catalog-list-item' class.
var allAnchorTags = $(".catalog-list-item a");
You can get the href attribute value by using .attr-method.
With the .replace-method you can replace the '/item/' string in front of the id.

Get link href and apply it to another link jQuery

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/

Find url and replace?

Is there any way I can do this... user presses a button, button finds all urls, example.com, and replaces it with sub.example.com?
If you want to replace all a.href attributes:
$(function(){
$('#buttonID').click(function(){
$('a').each(function(){
var newHref = $(this).attr('href').replace('example.com','sub.example.com');
$(this).attr('href',newHref);
});
});
});
Try this:
$('#replace-button').click(function() {
$('a[href="example.com"]').attr('href', 'sub.example.com');
});
To clarify, this is using the CSS attribute selector. The example finds a tags who have an href value of exactly 'example.com' - if your links had http://www. (or something like that) in front of them, this would not match them. There are more variations of the attribute selector, refer to http://css-tricks.com/attribute-selectors/ for examples.

Categories