Append new path in all the a href URL - javascript

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

Related

How can I get text from href?

I've got problem with getting this text from href. I'm working on dom and I'd like to get text from this href:
<div class='xx'>
<a href='zz' class='button>
...
I was trying to do sth like that:
document.getElementById(".xx").getAttribute("href")
But it's not working properly
But it's not working properly
Because
you don't have an element with id attribute .xx,
.xx targets the div not the anchor
Also, your anchor tag's attribute class is not closed properly, also closing tag is not given either.
<div class='xx'>
<a href='zz' class='button'>Some text</a>
</div>
you have a class so use the class selector itself using querySelector
document.querySelector( ".xx .button" ).getAttribute( "href" )
or simply
document.querySelector( ".xx .button" ).href;
getElementById will grab an element by that ID. You have an anchor (malformed albeit) with not an ID but a class. Secondly you are targeting the parent div. You should be targeting the tag using querySelector() instead. Then to get the href you'd use href.
const href = document.querySelector('.xx .button').href;
console.log(href);
<div class='xx'>
<a href='zz' class='button'></a>
</div>
This works for me
document.getElementsByClassName("xx")[0].getElementsByTagName("a")[0].getAttribute("href")
The code below will get text from link:
var x = document.getElementsByClassName('xx')[0].getElementsByTagName("a")[0].getAttribute("href");
you can use id instead of class because class returns undefined value.and also you tried to get class using getby id
wrong:
document.getElementById(".xx").getAttribute("href")
function h()
{
alert(document.getElementById("button").href);
}
<a href='zz' id='button' onclick='h();'>
asd</a>
var yourhref = document.querySelector("div.xx a.button").href
yourhref holds your requested value. This is as precise as it gets using only the part of code you provided. If somewhere else on the page you have a div with class xx and a link with class button you are not gonna have a good time.
Solution - either have your targeted element or parent have UNIQUE id and then write a selection from there.

How to use data attribute value as an ID selector in jQuery?

I need to use an ID as a selector by using a data attribute but I can't get it work.
Basically, I have a group of links at the very top. Each link have a unique id. I use these links to create a link on the fly. The link created on the fly has a data attribute set with the id of the one I previously clicked on. Now, I need to target this link with the data attribute using the Id of the link I clicked at first and show the inner text.
How can I set a data attribute (of an element created on the fly) as an ID selector?
Here is the following Javascript code.
$('.group-1 a').on('click', function(){
var block =
'<div class="group-2">' +
'<a href="#" class="child-item" data-item="'+ $(this).attr('id') +'" >Child Item 100</a>' +
'</div>';
$(block).appendTo( $('.host'));
});
$('body').on('click', '.child-item', function(){
var getId = $(this).attr('data-item');
var getInner = $('[id="#' + getid + '"]').text();
$('.result').text(getInner);
})
The HTML code:
<div class="group-1">
Parent Item 100
Parent Item 200
Parent Item 300
</div>
<hr>
<div class="host"></div>
<div class="result"></div>
I've prepared a live view at JSFiddle
The selector you want is not '[id="#myId"]', but '[id="myId"]' (there is no #):
$('[id="' + getId + '"]')
or, since you don't use special chars like ::
$('#' + getId)
Fixed JSFiddle here (notice you also had getid which I changed to getId).
Now, it pays to notice in these two cases there are two different selectors: the second is an ID selector, and the first is an attribute equals selector (that happens to be comparing the id attribute).
Important Differences Between the ID and Attribute-Equals selectors:
1) Elements with duplicated IDs
When there are elements with duplicated IDs (which is invalid HTML, but still can exist): the #foo selector only fetches the first matched element in the DOM (with the foo id); and the [id='foo'] selector fetches all of them.
2) Escaping
In the ID selector, the id is a CSS identifier, so it must match the CSS escaping rules.
In the attribute selector, the attribute value is a string.
For example, say your ID has a ":" in it:
$("#foo:bar"); // INVALID! :bar is intepreted as a (invalid) pseudo-class
$("#foo\\:bar"); // Valid! The : is properly escaped
$("[id='foo:bar']"); // Valid! The : is inside a string

Find a href and match a div

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();

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.

how to set href value on all elements with a given ID?

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

Categories