find and replace a unique html (href) string using javascript - javascript

Using Javascript, how can I change this classless anchor (assuming targeting unique href string):
to this, on page load:

You can select the element based on its href prop.
$('a[href="/unique-url-string/"]').prop('href', '/replacement-url-string/');
If you want to only search the pathname of these urls and keep the domain name the same you can try something like:
$('a').filter(function() {
return this.pathname === "/foo/bar"
}).prop('href', function () {
this.pathname = '/butt/butt/butt';
return this;
});

Using only JavaScript without library
function replaceLink(oldLink, newLink) {
var x = document.getElementsByTagName("a");
for(var i = 0; i < x.length; i++)
if(x[i].href == oldLink) {
x[i].href == newLink;
break;
}
}
}

Try this:
$(function(){
$('a[href="/unique-url-string/"]').attr('href', '/replacement-url-string/');
});
To replace a portion:
$(function(){
var a = $('a[href="/unique-url-string/"]');
a.attr('href', a.attr('href').replace('unique', 'replacement'));
});

var link = document.getElementById('linkToChange');
console.log(link.href);
link.href = "http://www.google.com";
me

Just do this :
$().ready(function(){
$('a').attr("href").replace("unique","replacement");
});

Related

Check if href equals a certain value

Currently im looping through links in a page and checking if the link contains a string to determine the url. Heres my current code:
$( ".domain a" ).each( function () {
if ($(this).is(':contains("imgur")')) {
This can detect if the element contains the string "imgur", but because of this is a link goes to a site like slimgur.com, it will also return true.
How can I properly check that the url is, in this example, imgur.com or any of its subdomains (i.imgur.com & m.imgur.com) and that a url such as slimgur.com wont return true?
Rather than check the text, use the properties associated to an <a> tag like hostname.
$( ".domain a" ).filter(function(){
return this.hostname === 'imgur.com';
}).doSomething();
DEMO
This will do it:
$( ".domain a" ).each( function() {
var str = 'imgur';
if($(this)[0].hostname.split('.').indexOf(str) > -1) {
console.log('Found ' + str);
}
})
You could do something like: JS Fiddle
$('a').each(function () {
var url = "yahoo.com";
var anchor = $(this).attr('href');
var domain = url_domain(anchor);
if (url === domain) {
//Do something here
}
});
function url_domain(data) {
var a = document.createElement('a');
a.href = data;
return a.hostname;
}
url_domain() function found here: Extract hostname name from string

How to get all the src and href attributes of a web site

I want a way to get all the src and href attributes(like images and links) in a website. How can i make this in javascript?
I try this:
var ilist=document.links;
for(var i = 0; i < ilist.length; i++) {
if(ilist[i].href) {
alert(ilist[i].href)
}
}
But for a something, this not works. Only works for . I want all href's and all src's for all tags. Can anybody help me?
Using plain JS you can do:
The string that we give querySelectorAll is just a normal CSS selector.
var srcNodeList = document.querySelectorAll('[src],[href]');
for (var i = 0; i < srcNodeList.length; ++i) {
var item = srcNodeList[i];
if(item.getAttribute('src') !== null){
alert(item.getAttribute('src'));
}
if(item.getAttribute('href') !== null){
alert(item.getAttribute('href'));
}
}
Here's the fiddle: https://jsfiddle.net/vpbepvco/1/
Using jquery you can run each on all elements with the all selector
$( "*" ).each(function() {
$(this).attr("src");
});
Use jQuery, but you have to take care about performance.
$("[src],[href]").each(function(){
var $el = $(this);
if( $el.is("a") ) {
// do some stuff with A element
} else if( $el.is("img") ) {
// do some stuff with A element
}
});

Changing href value from JavaScript

I have this example in JsFiddle.
http://jsfiddle.net/PtNfD/114/
Yahoo
Not working
$(document).ready (function () {
$('#changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
The href change works in the first link, but not in the second. How can I make it work for both links??
The number of links in my page is dynamic, because I create the links with PHP, so I need the href change to work in all generated links.
id attributes must be unique. You should convert the value changeMe to a classname for use on multiple elements. Then your existing code should work:
Yahoo
Not working
$(document).ready (function () {
$('.changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
Optionally, you could add a unique id to the second anchor tag and modify the JavaScript code accordingly.
You cannot use an ID on two different elements in HTML. You need to asign each of those a different ID or the same class instead and then apply your href change on each of the IDs, or the class
IDs should be used once per webpage. Classes can be used more plentifully. Remember your specificity. Use class instead of id: http://jsfiddle.net/PtNfD/115/
Yahoo
Not working
$(document).ready (function () {
$('.changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});

Replace all <a> tags in HTML string

Let's suppose that I have an HTML string containing some <a href=".."> tags. How can I replace all of them to translate this:
whatever
into this:
whatever
Any ideas?
You can use this regex on your string:
var re = new RegExp("<a href=\"([^\"]+)\"", "g");
result =
string.replace(re,
"<a href=\"#\" onclick=\"openLink('$1')\"");
http://regex101.com/r/wN0aB2
Update
To account for attributes before the href, you could use:
var re = new RegExp("<a([^>]* )href=\"([^\"]+)\"", "g");
result =
string.replace(re,
"<a$1href=\"#\" onclick=\"openLink('$2')\"");
http://regex101.com/r/bZ0nO4
You can easily do this using JS.
Find all anchor elements in DOM and setAttributes:
var anchors = document.getElementsByTagName("a");
for(var i =0; i < anchors.length; i++)
{ var myLink = anchors[i].getAttribute("href");
anchors[i].setAttribute("href","#");
anchors[i].setAttribute("onclick", "openLink('"+ myLink +"');");
}
Don't use RegExp, because it is very hard, if not impossible, to safely restrict the matches to just the anchor links that you are targeting. Instead you should use the very DOM parser that naturally every browser has built in.
And don't use onclick html attributes, because there is no need to tweak html in javascript to add javascript event handlers and it prevents users from using things like right click -> 'open in new tab', or 'copy link address'.
Use this:
var anchors = document.getElementsByTagName("a");
for (var i = 0 ; i != anchors.length ; i++) {
anchors[i].addEventListener("click", function (event) {
var href = this.getAttribute("href");
if (href) {
event.preventDefault();
openLink(href);
}
});
}
See jsfiddle
Or you can use a delegated event handler:
function openLink(href) {
alert("openLink " + href);
}
document.addEventListener("click", function (event) {
if (event.target.tagName === "A" && event.target.href) {
event.preventDefault();
openLink(event.target.href);
}
});
See jsfiddle
Or you can use jQuery:
$("a[href]").click(function (event) {
event.preventDefault();
openLink($(this).attr("href"));
});
See jsfiddle
result = subject.replace(/<a.*?href="(.*?)".*?>(.*)<\/a>/img, "$2");
http://regex101.com/r/dK2oU5

How to dynamically change the anchor tag link?

I'm trying to remove a landing page when I click on a link on a page. The page isn't mine so I'm trying to change the href with a user script.
Without any modification, the link looks like this:
https://www.domain.com/out.php?u=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPUZ1bC-1XjA%26amp%3Bfeature%3Drelated
What I want:
http://www.youtube.com/watch?v=PUZ1bC-1XjA&feature=related
What I got so far:
http://www.youtube.com%2fwatch%3fv%3dpuz1bc-1xja%26amp%3bfeature%3drelated/
But that adress doesn't work in the browser.
This is my current code:
$('a').each(function(index) {
var aLink = $(this).attr('href');
if(aLink) {
if(aLink.indexOf("out.php?u=") > 0) {
aLink = aLink.substring(51);
console.log(aLink);
$(this).attr('href', "http://"+aLink);
console.log($(this).prop('href'));
}
}
});
All help and tips are appreciated.
You need to decode the URL using decodeURIComponent
Change:
$(this).attr('href', "http://"+aLink);
To:
$(this).attr('href', 'http://' + decodeURIComponent(aLink));
Take a look at decodeURIComponent
You can also make use of the hostname, pathname, and search parameters of anchor elements.
// general function to turn query strings into objects
function deserialize_query_string(qs) {
var params = {};
var fields = qs.split('&');
var field;
for (var i=0; i<fields.length; i++) {
field = fields[i].split('=');
field[0] = decodeURIComponent(field[0]);
field[1] = decodeURIComponent(field[1]);
params[field[0]] = field[1];
}
return params;
}
$(document.links).each(function(i){
if (this.hostname=='www.domain.com' && this.pathname=='/out.php') {
var params = deserialize_query_string(this.search);
if (params.u) {
this.href = u;
}
}
});

Categories

Resources