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');
});
Related
when i input the command
document.getElementsByClassName('grid')[5] :
i get this :TEST
HOwever i struggle finding how to get the href value (a link here), i have thought about using GetAttribute but it does no work
That's because you're selecting the <div> parent instead of <a>, div's doesn't have href attribute.
You can get the href by doing:
const $parentDiv = document.querySelectorAll('.grid')[5];
const $anchor = $parentDiv.querySelector('a');
console.log($anchor.href);
You can use children property to get the tag, and get the href thereafter
There are 2 ways how you can do that
1 -
You can add an id attribute to the <a> tag and then use document.getElementById("yourid").getAttribute("href");
2 =
As mentioned by Eliabe Franca -
const $parentDiv = document.querySelectorAll('.grid')[5];
const $anchor = $parentDiv.querySelector('a');
console.log($anchor.href);
What this does is that it first gets the .grid[5] element and then gets the first <a> in it. The last line will help you get the href value.
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');
});
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...
My html looks like this
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_2854__a" href="https://www.kitty.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_2854__path"></div>
</a>
and
i am trying to find a greasemonkey script which changes the href part from ANYTHING to https://www.dog.com if the A class is jx_ui_html_a
so the result should be
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_2854__a" href="https://www.dog.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_2854__path"></div>
</a>
respectively
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_28254__a" href="https://www.dog.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_28254__path"></div>
</a>
Could you please help me in any way?
The following is two lines of code - the first one queries the DOM to find all a tags (document.querySelector('a') and converts it into an array (by passing it as an argument to [].slice.call), and the second runs a forEach function on the array, which reassigns the href attribute of every DOM Element in the array.
var anchors = [].slice.call(document.querySelectorAll('a');
anchors.forEach(function(element){
element.href = "http://www.dog.com/"
});
Same thing without forEach:
var anchors = document.querySelectorAll('a');
for(var i=0;i<anchors.length;i++){
anchors[i].href = "http://www.dog.com";
}
To limit the elements of anchors to only those with specific class name, supply it as part of the querySelector argument:
var anchors = document.querySelectorAll('a.jx_ui_html_a')
querySelector and querySelectorAll select elements the same way that rendering engines which apply CSS rules do. So you can pass it things like "p > a" (will return 'a' elements that are direct descendants of 'p' elements), and "div#container span" (which will return span elements that are anywhere inside the div with 'container' id).
querySelector returns the first match, while querySelectorAll returns an array-like list of all matching elements.
First you'll want to require jQuery. You can read about how to do that here.. Once that's installed you can run something like the following:
$(document).ready(function() {
$('.jx_ui_html_a').attr('href','http://www.dog.com');
});
In English, that will wait until the page is fully loaded ($(document).ready()), search for all elements with your specified class ($('.jx_ui_html_a')), and replace all of their href attributes with your specified URL.
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();