Adding data to hyperlink dynamically on click of another button by jQuery - javascript

I have an anchor with id='peter'. When i click this, the hyperlink of anchor 'jack' must now add the id of 'peter' at the end of its hyperlink.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$('#peter').click(function(){
$('#jack').attr('href', '?id=peter');
});
});
</script>
</head>
<body>
Click
Yahoo
</body>
</html>
Expectation:
the hyperlink of second anchor must now be -
http://www.yahoo.com?id=peter
Can someone help me out how to add this id by 'jQuery'?

Replace your existing javascript code with this code:
$(document).ready(function(){
$('#peter').click(function(){
var attr = $('#jack').attr('href') + "?id=peter";
$('#jack').attr('href', attr);
});
});

You have to append param to the href attribute:
var href = $('#jack').attr('href');
$('#jack').attr('href', href + '?id=peter');

One way can be to replace the href attribute:
$('#jack').attr('href', 'http://www.yahoo.com?id=peter');
Another option is to add it at the end of the current value:
var href = 'http://www.yahoo.com'
$('#jack').attr('href', href + '?id=peter');

Related

How to change href value using javascript?

I have a wordpress site and theme that is providing me an ability to change elements in menu widget on all pages it appears only.
So, what I want to do is to change links and names of menu elements locally on one page. I have an id's for menu li elements, 'menu-item-7062' for example and a href tag inside it with already defined link and text values.
I have already tried and injected this code snippets in after all post content:
<script type='text/javascript'> document.getElementById('menu-item-7062').href = 'new link'; </script>
I have also created a function that is triggers after onclick event:
<script type="text/javascript">
document.getElementById("menu-item-7062").onclick = function() {
document.getElementById("menu-item-7062").href="my new link";
};
</script>
Unfortunately, they didn't affect my old link. Returning to my question, what are other solutions I could try in order to change both a href link and text value? What possible mistakes I have made?
UPDATED:
Here is my anchor tag
Автоматизация технологических процессов
A tag located under the <li id="menu-item-7062">, there is my mistake.
Did you try setAttribute function
document.getElementById("menu-item-7062").setAttribute("href", "my new link");
I have successfully affected a tag by query selector:
<script type="text/javascript">
var tag = document.querySelector('a[href="https://test.etm.io/ru/services/automation/"]');
if(tag){
tag.innerHTML = "new";
}
</script>
you should try this..
var a = document.getElementsByTagName("a");
a[0].href = "www.abc.com/";
if you doesn't know index of a then you should get id of a and then set link.
This will help you to check and set href for tag "a" without "id":
const parent = document.getElementById("menu-item-7062");
if(parent.firstElementChild.localName === 'a') {
const child = parent.firstElementChild;
child.href = 'my new link';
}
OR
const parent = document.getElementById("menu-item-7062");
parent.firstElementChild?.href = 'my new link';

Replace href link from contextmenu after right-click and choosing one of "open..."

I can get into contextmenu object and disable it (How to add a custom right-click menu to a webpage?), but how can I replace original href from a link object, when user right-click on it and choose "open in a new tab" or "open in a new window" or "open in an incognito window"?
In fact I found a better/simpler way to achieve it. replaceLink() is responsible for replacing centextmenu links here:
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
majkesz.pl<br>
<script>
document.getElementById("lol").onclick = function(event) {
event.preventDefault();
window.location.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
return false;
};
function replaceLink(e) {
e.target.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
}
</script>
</body>
</html>
unfortunatelly above solution is not working for middle click of mouse for FF and newer chrome. instead use generic:
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
majkesz.pl<br>
<script>
function replaceLink(e) {
e.target.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
}
</script>
</body>
</html>
It seems to me that you wouldn't be able to do that for security reasons. For interacting with the context menu you can check out this library http://ignitersworld.com/lab/contextMenu.html.
EDIT: You can try this, although its a little hacky.
<html>
<head>
</head>
<body>
Google
<script>
// get all anchor elements
var anchors = document.getElementsByTagName("a");
for(var i=0; i<anchors.length; i++){
var el = anchors[i];
// add event listener on each anchor element
el.addEventListener('contextmenu', function(ev) {
// get the original href value of the element
var originalTarget = el.href;
// change it to what you want to go to
el.href = 'http://www.amazon.com';
// asynchonously change it back to the original
setTimeout(function(){
el.href = originalTarget;
},1);
}, false);
}
</script>
</body>
</html>
it adds an event listener on all anchor elements and changes the href when the context menu event is fired, and after that it changes it back to its original value. Hope it works for you.

Get html node on href click

In my html page I want to get html node on its href click.
example:
HTML FILE
<!DOCTYPE html>
<html>
<body>
<p>Click1</p>
<p>Click2</p>
</body>
</html>
When Click1 is clicked I want to value: W3
When Click2 is clicked I want to value: google
Currently, I am using document.documentElement.outerHTML to get complete html string and parse it. Is there a better way to get data-type value on a href click?
jQuery:
$('a').click(function(){ console.log( $(this).data('type') ) })
JavaScript:
var link = document.querySelectorAll('a');
for (var i = 0; i < link.length; i++) {
link[i].addEventListener('click', function(e) {
console.log(this.dataset.type)
});
}

Im trying to use a click function which uses 'this' as to get the value after the last '/' in the URL by using split('/') or lastindexof('/')

I am triggering a click() function which will grab the users url link from an anchor tag and then I am trying to grab the end part of the URL which contains the username.
I can do this with out using $(this) but this has become a requirement and I need it done this way.
Please see the snippet to better understand.
$('a[href]').click(function(e) {
e.preventDefault();
var test = this;
// works fine
alert(test)
// doesn't work
alert(test.substring(test.lastIndexOf('/') + 1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<p>
I need to get the end part of the URL(john)
</p>
</div>
click here
Any ideas?
this will be a reference to the DOM element, the anchor, not to the anchor's href property.
Try var test = this.href;
$('a[href]').click(function(e) {
e.preventDefault();
var test = this.href;
// doesn't work
alert(test.substring(test.lastIndexOf('/') + 1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<p>
I need to get the end part of the URL(john)
</p>
</div>
click here
You can just do this:-
$('a[href]').click(function(e) {
e.preventDefault();
var test = this;
// works fine
alert(test.href) // use `test.href` instead of just `test`
// works fine now
alert(test.href.substring(test.href.lastIndexOf('/') + 1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<p>
I need to get the end part of the URL(john)
</p>
</div>
click here
The error is because test is the html 'a' element and not the url itself. Use test.href to access the url string.
Replace the javascript with:
$('a[href]').click(function(e) {
e.preventDefault();
var url = this.href;
alert(url.substring(url.lastIndexOf('/') + 1));
})
Refer the jsfiddle here for a working example.

onclick does not fire in a link that is created by clicking another link

Javascript function writelink creates a link that fires function hiya. It works when I define and invoke writelink inside script. But, I want the body to contain another link that calls writelink to create a link. This final link fails to fire (but works if I replace hiya with alert). I am a total novice, so I hope it is something obvious. The main idea is that I have to create some links from code, and these have to fire to execute some more code. (If you want me to do this a totally different way, please try to give me a complete example.)
<HTML>
<HEAD>
<script>
function hiya (num){
alert("hiya " + num);
}
function writelink (num){
var htmlstr = "link" + num + "";
document.write(htmlstr);
}
writelink(1);
</script>
</HEAD>
<BODY>
<br>
link2;
<br>
</HTML>
document.write(htmlstr) replaces the entire DOM with the link / htmlstr you are about to insert. Use pure javascript to create the link(s) instead :
function writelink(num){
var link = document.createElement('a');
link.innerHTML='link '+num;
link.href='#';
link.onclick=hiya(num);
document.body.appendChild(link);
}
Just replace writelink() with the code above.
You would typically want to add the link to a certain element instead of just <body>, lets say a <div> with the id menu :
var cnt = document.getElementById('menu');
cnt.appendChild(link);
update
<!doctype html>
<html>
<head>
</head>
<body>
link2
<script>
function hiya(num) {
alert("hiya " + num);
}
function writelink(num){
var link = document.createElement('a');
link.innerHTML='link '+num;
link.href='#';
link.onclick=function(e) {
hiya(num);
}
document.body.appendChild(link);
}
writelink(1);
</script>
</body>
</html>

Categories

Resources