Set link href with javascript

How to change href attribute using JavaScript after opening the link in a new window?

And the goal is to follow this link (opening in a new tab) and change its attributes (on previous tab). I mean we open google.com in a new tab and if we look back on the link, it’s refreshed. I’ve tried this js code

But it also changes the target of new opening tab. Instead of opening google it opens facebook in my example. Is it possible to fix it?

7 Answers 7

Your onclick fires before the href so it will change before the page is opened, you need to make the function handle the window opening like so:

You can delay your code using setTimeout to execute after click

onclick="changeLink(); return false;" 

to cancel its default action

You can change this in the page load .

My intention is that when the page comes to the load function, switch the links (the current link in the required one)

Well in my own Case it was a react code i used a map method on my nav links and the href attibute simply takes you to to the place in the page.

i needed a new tab only on the blog nav. The set Attribute opens a new tab but it doesnt default to the new tabs origin and it refreshes the whole page. But this solution worked for me.

const handleBlogClick = (event) => < const navLink = document.querySelectorAll("#nav-link"); if (event.target === navLink[4]) < const blogNav = navLink[4]; console.log(blogNav); console.log(event.target.innerHTML); window.open( "https://www.linkedin.com/company/ideas-worth-billions/", "_blank", "noopener,noreferrer" ); blogNav.innerHTML = "Blog"; return false; >>; 
document.getElementById("myLink1").onclick = function() < window.open("http://www.facebook.com"); return false; >; document.getElementById("myLink2").onclick = function() < window.open("http://www.yahoo.com"); return false; >; 

Is there any downside of leveraging mousedown listener to modify the href attribute with a new URL location and then let the browser figures out where it should redirect to?

It’s working fine so far for me. Would like to know what the limitations are with this approach?

// Simple code snippet to demonstrate the said approach const a = document.createElement('a'); a.textContent = 'test link'; a.href = '/haha'; a.target = '_blank'; a.rel = 'noopener'; a.onmousedown = () => < a.href = '/lol'; >; document.body.appendChild(a); > 

Источник

Don’t do that, please. It kills the ability to view the link with a mouse over, and kills the ability to middle or right click the link. Instead, bind to the on-click event for the link and return false to prevent the browser from following the link.

@Cory Larson, I don’t think many web programmers would think the first time they read «set links (href) in the page». I don’t think many beginning web programmers would think that, either.

Instead of arguing over pedantry, how about upvoting my answer to the top so the OP doesn’t commit this evil? 😉

3 Answers 3

DON’T CHANGE HREF TO #

Set the onclick function to return false instead.

This will have the same effect, whilst allowing greater usability.

Here’s a quick example (using jQuery, but works with anything):

jQuery('a').click( doStuff ); function doStuff() < // . function body. return false; >

This works because the value you return from an onX event function determines whether that event continues firing or stops. Return true to allow it to continue or false to stop it.

With onclick this means the click is stopped (so the link isn’t followed) — however it still allows people to interact with the link via middle and right click (e.g. opening in new tab, adding to bookmarks, and so on)

For another example, with onkeypress you can return false to prevent the character typed from being added to an input control (for example, you could mimic the HTML5 input=»numeric» control by having an onkeypress that returned false for any non-numeric characters).

Источник

Change the href of an anchor tag with javascript

Hey I have a question for javascript. I need to assign an href value to an anchor tag or asp:HyperLink. SOMETHING. that will allow me to link text in a dialog popup to an href that a function specifies. Here is my code.

 //I will spare you all of the div tags for formatting 

Now I am having to get an fso from the database since that is where the info is stored. This fso is different depending on what the entity reflector class sends to this javascript. I have a function that formats javascript strings similar to C# I found. I then have another function that gets the fso from the entity reflector class. This works. I tested the string by displaying it in an alert and this works fine. The problem I am having is setting the href of the anchor tag with javascript. I am going nuts! Please help! String Format:

String.format = function() < var s = arguments[0]; for (var i = 0; i < arguments.length - 1; i++) < var reg = new RegExp("\\", "gm"); s = s.replace(reg, arguments[i + 1]); > > 
function changeHref(fso) < var downloadHref = String.format("Download.ashx?fso=", fso); $('#').href = downloadHref; showDialog(); > 

The download link is changed and everything. I just cannot seem to be able to set this! Am I missing the order of the page load? Do I need to do this after the whole page loads since items might not be generated yet? I tried a couple different things. I really could use a direction.

Источник

will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. «anchor») anchor tags:

. Then you probably don’t want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match tags with an existing href attribute:

Of course, you’ll probably have something more interesting in mind. If you want to match an anchor with a specific existing href , you might use something like this:

$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/') 

This will find links where the href exactly matches the string http://www.google.com/ . A more involved task might be matching, then updating only part of the href :

$("a[href^='http://stackoverflow.com']") .each(function() < this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, "http://stackoverflow.com"); >); 

The first part selects only links where the href starts with http://stackoverflow.com . Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you — any sort of modification to the link could be done here.

For completeness, since this is still being linked to occasionally, I’ll add that since jQuery 1.4, the last example doesn’t require using each — the following would now be possible: $(selector).attr(‘href’, function() < return this.replace(/. /, '. '); >);

@DavidHedlund your function doesn’t work. It produces «this.replace is not a function». It should be: $(‘a[href]’).attr(‘href’, function(i, val) < return val.replace(/.*/, 'xy')>);

With jQuery 1.6 and above you should use:

$("a").prop("href", "http://www.jakcms.com") 

The difference between prop and attr is that attr grabs the HTML attribute whereas prop grabs the DOM property.

You can find more details in this post: .prop() vs .attr()

An explanation why you should use prop over attr would be appreciated, for people coming to the question and finding attr apparently working perfectly fine in newer jQuery versions.

Use the attr method on your lookup. You can switch out any attribute with a new value.

$("a.mylink").attr("href", "http://cupcream.com"); 

Even though the OP explicitly asked for a jQuery answer, you don’t need to use jQuery for everything these days.

A few methods without jQuery:

var anchors = document.querySelectorAll('a'); Array.prototype.forEach.call(anchors, function (element, index) < element.href = "http://stackoverflow.com"; >); 
var anchors = document.querySelectorAll('a[href]'); Array.prototype.forEach.call(anchors, function (element, index) < element.href = "http://stackoverflow.com"; >); 
var anchors = document.querySelectorAll('a[href*="google.com"]'); Array.prototype.forEach.call(anchors, function (element, index) < element.href = "http://stackoverflow.com"; >); 
var anchors = document.querySelectorAll('a[href^="https://"], a[href$=".png"]'); Array.prototype.forEach.call(anchors, function (element, index) < element.href = "http://stackoverflow.com"; >); 

..no need for regex, in most cases.

Depending on whether you want to change all the identical links to something else or you want control over just the ones in a given section of the page or each one individually, you could do one of these.

Change all links to Google so they point to Google Maps:

 $("a[href='http://www.google.com/']").attr('href', 'http://maps.google.com/'); 

To change links in a given section, add the container div’s class to the selector. This example will change the Google link in the content, but not in the footer:

 

. link to Google in the content.

Links: Google
$(".content a[href='http://www.google.com/']").attr('href', 'http://maps.google.com/');

To change individual links regardless of where they fall in the document, add an id to the link and then add that id to the selector. This example will change the second Google link in the content, but not the first one or the one in the footer:

 

. link to Google in the content.

. second link to Google in the content.

Links: Google
$("a#changeme").attr('href', 'http://maps.google.com/');

The simple way to do so is :

Attr function (since jQuery version 1.0)

$("a").attr("href", "https://stackoverflow.com/") 

Prop function (since jQuery version 1.6)

$("a").prop("href", "https://stackoverflow.com/") 

Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.

Now, there are lot of ways to identify exact anchor or group of anchors:

Quite Simple Ones:

  1. Select anchor through tag name : $(«a»)
  2. Select anchor through index: $(«a:eq(0)»)
  3. Select anchor for specific classes (as in this class only anchors with class active ) : $(«a.active»)
  4. Selecting anchors with specific ID (here in example profileLink ID) : $(«a#proileLink»)
  5. Selecting first anchor href: $(«a:first»)

More useful ones:

  1. Selecting all elements with href attribute : $(«[href]»)
  2. Selecting all anchors with specific href: $(«a[href=’www.stackoverflow.com’]»)
  3. Selecting all anchors not having specific href: $(«a[href!=’www.stackoverflow.com’]»)
  4. Selecting all anchors with href containing specific URL: $(«a[href*=’www.stackoverflow.com’]»)
  5. Selecting all anchors with href starting with specific URL: $(«a[href^=’www.stackoverflow.com’]»)
  6. Selecting all anchors with href ending with specific URL: $(«a[href$=’www.stackoverflow.com’]»)

Now, if you want to amend specific URLs, you can do that as:

For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:

$("a[href^='http://www.google.com']") .each(function() < this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) < return "http://proxywebsite.com/?query mt24"> 
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
answered Mar 30, 2018 at 4:51
Add a comment |
15

Try this;

$("#link").attr("href", "https://coenvink.com/") 

A breakdown of what the code does:

This part of the code gets the element with id "Link". After this you set the attribute 'href' (witch is basically the link-to-url) to your new url, witch, in this case, is my own website:

.attr("href", "https://coenvink.com/") 

Источник

Читайте также:  Функция в java это
Оцените статью