Modify all links' href attribute using plain javascript only - javascript

I have an email template to send on a shipping notification that includes a shipping tracking number as below and I need to clear all the spaces from href using plain javascript:
<a class="press-bt" id="clearSpace" href="https://www.royalmail.com/track-your-item?trackNumber=JX12 0008 990 90GB">TRACK</a>
I can get it right using jQuery but not using Javascript
I am trying to do it this way:
window.onload = function() {
var str = document.getElementById("mylink");
document.write( str.replaceAll("\\s+","") );
});
Working code using jQuery:
$(document).ready(function() {
$('a').attr('href', function (_, val) {
return val.replace(/\s/g, '');
});
});

You should, if possible, remove the spaces server-side. I hope you understand no javascript will run in the emails you send.
// This prevents multiple `window.onload` conflict
window.addEventListener("load", clearLinks);
// This allows you to call the function even later if needed
function clearLinks() {
// Get list of all links in the page
var links = document.getElementsByTagName("a");
// Loop through links
for(var i=0,l=links.length; i<l; i++) {
// No need to use `getAttribute`, href is defined getter in all browsers
links[i].href = links[i].href.replace(/\s/g, "");
}
}
In modern browsers, you can replace the for loop with Array.prototype.forEach. This method can be normally called on arrays ([ ... ]), but the list returned by getElementsByTagName is not an array, so use this trick:
function clearLinks() {
var links = document.getElementsByTagName("a");
// Loop through links
Array.prototype.forEach.call(links, function(link) {
link.href = link.href.replace(/[cC]/g, "c");
});
}
Search for Function.prototype.call to learn more about calling functions on objects.

Target the element by its id, grab the href attribute, and set it again by removing the spaces.
var link = document.getElementById("mylink");
var href = link.getAttribute('href');
link.setAttribute('href', href.replace(/\s/g, ''));

Related

javascript pass media EventListener to html (html5) media.currentTime

*update here is my code edit as you see working) https://codeshare.io/a3ZJ9g
i need to pass on a javascript varible to a html link...
my original question was here HTML5 video get currentTime not working with media events javscript addEventListener
working code:
<script>
var media = document.getElementById('myVideo');
// durationchange
var isdurationchange = function(e) {
$("#output").html(media.currentTime);
var x = document.createElement("a");
};
media.addEventListener("timeupdate", isdurationchange, true)
</script>
that code works
but i need it to echo the currentTime value to the html page such as
document.write("<a href=/time.htm?currentTime='.media.addEventListener("timeupdate", isdurationchange, true).'>link</a>;);
so it would print out
<a href=time.htm?currentTime=currenttimefromjavascript>link</a>
thank you
i did read:
how to pass javascript variable to html tag
How can I pass value from javascript to html?
someone suggested:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};
but where does that go?
document.write tries to write to the current document. If the document has already been processed, the document will be replaced with a blank one with your argument. You don't want that; use the proper DOM methods instead.
If, for an element you create dynamically, you want to change its href on every timeupdate, you would do:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};

How to get anchor text in a Session variable?

I am working on a project in which i have linked many pdf files in the master page.On clicking the anchor the page redirected to the specified page and displays pdf in iframe.Now i want the text in anchor tag to be displayed on the page where pdf is opened.
Consider I have an anchor which looks like this :
News Letter
Now i want the text " News letter" to be shown on the redirected page.
I think i could this by saving the text in session variable.But How can I save the anchor text in Session variable without specifying any id or class to the anchor tag? Can anyone help me please ?
You probably looking for QueryString instead of session, You are already passing path in QueryString, also pass the anchor text. You need to add this to url while you are creating the anchor tag.
News Letter
On server side
lblForAnchor.Text = Request.QueryString["aText"].ToString();
Edit you can not change the query string when it is created then you can change it when it is loaded in DOM in document.ready. Assign a class to your anchors to be specific.
$( 'a.someclass' ).attr( 'href', function(index, value) {
return value + '&aText=' + $(this).text();
});
Other way to do this on click of anchor.
$( 'a.someclass' ),click(function(event) {
window.location.href = this.href + '&aText=' + $(this).text();
});
You can try this
$("a").click(function (e) {
if($(this).attr("href").match(".pdf$"))
{
window.location.href = $(this).attr("href") + "&title=" + $(this).text();
e.preventDefault();
}
});
On server side in "Main_Content.aspx"
strTitle = Request.QueryString["title"];
You could Write the content dynamically with javascript:
News Letter
Javascript:
<script language="javascript">
function openWin(t,u) {
docstring='<iframe src='+u+'></iframe>';
win = window.open();
newdoc=win.document;
newdoc.writeln(t);
newdoc.write(docstring);
newdoc.close();
}
var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
var theAnchor = elements[i].innerHTML;
var theHref = elements[i].href;
if(theHref.match(/\.pdf/)){
openWin(theAnchor,theHref);
}
}
</script>
Or call a different address with URL and test as parameters and generate the doc on the server side.
I'm not sure how this will behave with the link click but it might be worth a shot.
links should not have to be modified.

Add certain end to all the internal links on the page

I need some simple code on pure JavaScript (NOT jQuery!) that will add certain end to all the internal links on a page (i.e. to all the links that contain website domain in its href attribute), something like:
var pagelinks = document.getElementsByTagName('a');
for(var i in pagelinks) {
if(pagelinks.getAttribute('href').indexOf(document.domain) != -1) {
pagelinks[i].setAttribute('href',currenthref+'my_end');
}
}
!!! NOTE: it's not working script — it's only "something like" what I need
For example the internal links on a page are:
Showcase
Contacts
...
I need
Showcase
Contacts
...
If I understand your question correct this is what you want:
var domain = 'www.youtube.com';
var pagelinks = document.getElementsByTagName('a');
for (var i = 0; i < pagelinks.length; i++) {
var current = pagelinks[i].getAttribute('href');
if (current.indexOf(domain) !== -1) {
pagelinks[i].setAttribute('href', current + '?my_end');
}
}
Updated fiddle: https://jsfiddle.net/cm69qmnL/6/
You have to specify the domain you want to check the href attributes against and then run a loop which checks each anchor's href attribute, checks it against the specified domain and updated the href if the domain exists in current.

Is there a way to open all <a href> links on a page in new windows?

I have a bunch of <a href=".html"> links and want to make them all open in new windows.
I know I can do a search and replace all to add target="_blank" to all my <a href="..."> links.
However, is there a quick way, such as setting a CSS style, or adding some JavaScript code, to accomplish the same thing?
If you have a page consisting of only links, consider <base target="_blank">. This opens every link in a new window (but also includes the targets of forms, unless overridden with <form target="_self">.
As others have shown, without modifying the HTML source, you can use Javascript to iterate through all <a> tags and add the target attribute or add an event listener that sets the target attribute dynamically.
If you have jQuery it's simple
$("a").attr("target", "_blank");
Or regular Javascript
var links = document.links;
for (var i = 0; i < links.length; i++) {
links[i].target = "_blank";
}
As per #Lekensteyn's suggestion, without Javascript (added for Completeness)
<base target="_blank">.
CSS: No.
JavaScript: Delegate a click event, which adds a target="_blank" attribute on click of a link.
document.body.addEventListener(function(e) {
if (e.target.nodeName.toUpperCase() === 'A' && e.target.href) {
e.target.target = '_blank';
}
}, true);
Note: If the <a> element contains other elements, you might want to traverse the tree to find out whether an anchor element is clicked:
document.body.addEventListener(function(e) {
var target = e.target;
do {
if (target.nodeName.toUpperCase() === 'A' && target.href) {
target.target = '_blank';
break;
}
} while (target = target.parentElement);
}, true);
Or, if you're a jQuery-lover:
$('body').on('click', 'a', function(e) {
e.target.target = '_blank';
});
yep, u can add attribute with JS to all links in HTML document named 'target' with value '_blank' ;)
You could also open replace href's of all links from url to javascript:openInWindow(url) using this, and writing function in JS that opens new window and set's it's location to url ;) Google will help you with both.
Just add a html base element to the page using Javascript:
var e = document.createElement("base");
e.target = "_blank";
document.head.appendChild(e);
I've used pure vanilla JavaScript to create a script that makes all the links open in a new window.
<script type="text/javascript">
var all_links = document.querySelectorAll("a");
for (let index in all_links) {
try {
all_links[index].setAttribute("target", "_blank");
}
catch (error) {
//console.log(error);
}
}
</script>

Make all hyperlinks in the site do nothing

I want to make a script that disables hyperlinks and instead fires a function when one is clicked.
should work as
<a onclick="talk('http://google.com)'></a>
Is there a way to know when the wants to redirect and instead run "talk()" or display an alert window?
var anchors = document.getElementsByTagName('a');
for (var a = 0; a < anchors.length; a++){
anchors[a].href = "javascript:talk('" + anchors[a].href + "');";
}
Use some discretion though...
This solution uses (DOM Level 0) event handling instead of touching the href directly.
(function () {
var anchors = document.getElementsByTagName('a'),
i = anchors.length;
while (i--) {
anchors[i].onclick = function () {
talk(this.href);
return false;
};
}
}());
Edit: The benefit of this approach is it's much simpler to put the href back when you want to. Given an anchor tAnchor, you merely need to unset the onclick attribute:
tAnchor.onclick = null

Categories

Resources