How to get href value using jQuery? - javascript

I'm trying to get href value using jQuery:
<html>
<head>
<title>Jquery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function(event) {
alert("As you can see, the link no longer took you to jquery.com");
var href = $('a').attr('href');
alert(href);
event.preventDefault();
});
});
</script>
</head>
<body>
jQuery
</body>
</html>
But it doesn't work. Why?

You need
var href = $(this).attr('href');
Inside a jQuery click handler, the this object refers to the element clicked, whereas in your case you're always getting the href for the first <a> on the page. This, incidentally, is why your example works but your real code doesn't

You can get current href value by this code:
$(this).attr("href");
To get href value by ID
$("#mylink").attr("href");

It's worth mentioning that
$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always

It works... Tested in IE8 (don't forget to allow javascript to run if you're testing the file from your computer) and chrome.

if the page have one <a> It Works,but,many <a> ,have to use var href = $(this).attr('href');

Assuming you have this html :
<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>
You can get and display the href attribute with this JS snippet :
<script>
$(".linkClass").click(function() {
alert($(this).attr("href"));
});
</script>

**Replacing href attribut value to other**
<div class="cpt">
testoneLink
</div>
<div class="test" >
testtwoLInk
</div>
<!--Remove first default Link from href attribut -->
<script>
Remove first default Link from href attribut
$(".cpt a").removeAttr("href");
Add Link to same href attribut
var testurl= $(".test").find("a").attr("href");
$(".test a").attr('href', testurl);
</script>

If your html link is like this:
<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>
Then you can access the href in jquery as given below (there is no need to use "a" in href for this)
$(".linkClass").on("click",accesshref);
function accesshref()
{
var url = $(".linkClass").attr("href");
//OR
var url = $(this).attr("href");
}

Related

Add target blank to JavaScript generated link

The script is used in a php file and it diplays a linked alexa rank image:
<script type="text/javascript" src="http://xslt.alexa.com/site_stats/js/t/a?url=x-invest.net"></script>
This is the result:
<a class="AlexaSiteStatsWidget" href="http://www.alexa.com/data/details/main?url=http://xxx">
<img alt="Alexa Certified Site Stats for xxx" src="http://xsltcache.alexa.com/site_stats/gif/t/a/eC1pbnZlc3QubmV0/s.gif" border="0">
</a>
I want to get target="_blank" in the < a > tag.
This is what i tried already:
<script>document.getElementsByClassName("AlexaSiteStatsWidget").setAttribute('target', '_blank');</script>
<script>$('#AlexaSiteStatsWidget a').attr('target', '_blank');</script>
But they both dont work.
Just change this:-
<script>document.getElementsByClassName("AlexaSiteStatsWidget").setAttribute("target","_blank");</script>
To this :-
<script>document.getElementsByClassName("AlexaSiteStatsWidget")[0].setAttribute("target","_blank");</script>
And remove this line :-
<script>$('#AlexaSiteStatsWidget a').attr('target', '_blank');</script>
I don't know if it's gonna work but if you create an event listener on your <body>'s <a>s elements like this:
<script type="text/javascript">
document.querySelector("body a.AlexaSiteStatsWidget").addEventListener("click", function() {
this.setAttribute("target", "_blank");
});
</script>
I didn't test it but i guess it gives you an idea of what i want to say
getElementsByClassName returns an array of all nodes (html elements) with the class name provided. If you only have one html element with the specified class, it will still return an array containing one node.
If you want to apply this to one <a> element use:
<script>
document.getElementsByClassName("AlexaSiteStatsWidget")[0].setAttribute('target', '_blank');
</script>
If want to apply this to multiple <a> elements:
<script>
var alexaArray = document.getElementsByClassName("AlexaSiteStatsWidget");
for(var i = 0; i < alexaArray.length; i++){
alexaArray[i].setAttribute('target', '_blank');
}
</script>

Change URL - Javascript

I am tying to change the href link using JavaScript. In my example I would like to change the url path from "linktwo.html" to "problem3.html.
I know that there are probably easier ways of doing this, but this is for practice purposes.
Using my example as below, what am I doing wrong to change the href?
HTML:
<body onload="changeLink()">
<div id="p">
<h1> first link </h1>
</div>
<div id ="q">
second link
</div>
Javascript:
<script type="text/javascript">
function changeLink(){
document.getElementById("q").href.innerHTML="problem3.html";
}
</script>
Option One :
Change the Java Script as below
<script type="text/javascript">
function changeLink(){
document.getElementById("q").href.innerHTML=" second link ";
}
</script>
Option Two :
change the code as below
HTML :
<body onload="changeLink()">
<div id="p">
<h1> <a id ="p1" href="linkone.html"> first link </a></h1>
</div>
<div id ="q">
<a id ="q1" href="linktwo.html"> second link </a>
</div>
JAVA SCRIPT :
<script type="text/javascript">
function changeLink(){
document.getElementById("q1").removeAttribute("href");
document.getElementById("q1").setAttribute("href","problem3.html");
}
</script>
Please check following code
<script type="text/javascript">
function changeLink(){
document.getElementById("q").href ="problem3.html";
}
</script>
First, you should put the ID on the link itself, not the containing div.
second link
Then, you should use the href property without innerHTML.
function changeLink(){
document.getElementById("my_link").href = "problem3.html";
}
Give an id for the href
</head>
<body onload="changeLink()">
<div id="p">
<h1> first link </h1>
</div>
<div id ="secondDiv">
second link
</div>
and remove the innerHTML part from the javascript:
<script type="text/javascript">
function changeLink(){
document.getElementById("q").href = "problem3.html";
}
</script>
You can also do:
<a id="changeurl" href="linktwo.html"> second link </a>
Give your anchor an id and then in the script area:
link = document.getElementById('changeurl');
link.removeAttribute('href');
link.setAttribute('href','problem3.html');
First you get the object. Then you remove the current href attribute. After that you can add a new one! Hope this helps and better answers your question.
Thank you all for the helpful information! Further experimenting resulted in me coming up with changing my javascript to this.
function changeLink(){
document.getElementById("q").childNodes[1].href="problem3.html";
Not sure if this is practical or not but was an added solution to everyones solutions.

Using jquery to write information from other parts of the document

<script type="text/javascript" src="jquery.js"></script>
<script>
var printLinks = function () {
var links = $(.info).code;
document.write(links);
};
</script>
<form>
<input type="button" value="printlinks" onclick="printLinks()"></input>
</input>
</form>
I am trying to write to a document all of the text in a certain element type that is a child of an element I query by class $(.info). I know document.write is not the best method for writing to a document. info is the class of the parent element of the <code> tags that contain the links I want to print. I am very new to jQuery so I am probably misusing it. Any help would be appreciated.
Okay, if I understand correctly, you want to grab the content in the element with the class info. If that is correct you want to take the following approach:
<script type="text/javascript">
function printLinks() {
var content = $('.info').html(); // Grab innerHTML of element
$('#idOfTargetElement').html( content ); // write the content here
}
</script>
EDIT:
See this fiddle for clarification:
http://jsfiddle.net/XD5qj/
You can use the html() function of jQuery.
For example:
<script>
$(function(){
var links = $('.info code').html();
$('.output').html(links);
});
</script>
<div class="info"><code>Example code</code></div>
<div class="output"></div>
If you have multiple "< code>" tags, you want to use the handy "each()" function of jQuery:
$('.info code').each(function(){
$('.output').append($(this).html());
});

Dynamically load link in rel attribute.

I want to dynamically load content using jquery's .load() function. Im storing the links in the .rel attribute of the links. I've got it setup like this:
<script>
$(document).ready(function(){
$('.sidebar_link').click(function(){
var link = this.attr('rel');
event.preventDefault();
$('#content').empty();
$('#content').load(link '#content');
});
});
</script>
<div class="main_menu">
<a class="sidebar_link" href="#" rel="photos.htm">Photography</a>
<a class="sidebar_link" href="#" rel="furniture.htm">Furniture</a>
<a class="sidebar_link" href="#" rel="services.htm">Services</a>
</div>
</div>
Its not working - It doesn't seem to be grabbing the link out of the rel attribute and Im not sure why. Any ideas?
Try this:
var link = $(this).attr('rel');
.attr is not a native JavaScript function, it is from jQuery so you have to wrap this with jQuery
And this:
$('#content').load(link);
You can pass an id for loading fragments, however the url and the id need to be a string literal like so $('#content').load('photos.htm #content') The photos.htm page would need to have an element on the page with id content. If you just want to display the entire contents of the page, just use the url.
In your click handler this is a pure dom element; you need to call the jQuery function on it before accessing the rel attribue
$('#content').load($(this).attr("rel"));
$('#content').load(link '#content');
This is almost certainly throwing a syntax error -- check your JavaScript console. I think you just want .load(link);.

jQuery problem, jQuery takes over all links on page

<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
$("#results").load( "jquery-routing.php", { pageNo: $(this).text(), sortBy: $("#sortBy").val()} );
return false;
});
});
</script>
<div id="results"> </div>
1
2
that code works fine, only problem that after I run it all my a href links stop to work! The links become jquery ajax calls.. why?
You're $("a") selector matches all <a ...> tags, you need to change it to something more specific:
$("a#someid")
$("a.someclass")
$("div#somecontainer a")
To target specific links, use the id or class tag on your anchor tags.
E.g.
<a class="link1" href=""></a>
<a id="link2" href-""></a>
Do note that id tags are unique within a page and can only be used once.
Reference those links in jQuery using:
$('a.link1').click(function() {}
$('#link2').click(function() {}
or you can combine both:
$('a.link1, #link2').click(function() {}
What you need to do is assign an id or class tag to the link that will call the ajax request. E.g. <a class="ajax" href="">ajax</a> and referencing it with $('a.ajax').click(function () {}
Your setting the onclick event of all anchor tags on the page. Try only selecting the link that you want instead of the more general $("a")
Your selector $("a") indicates all the hiperlink in your page.
You may need to give a specific id to the hiperlink where you want your ajax call to work and then change the selector based on that.
ex:
<a id= "my-link" href="" >ddd</a>
$("a#my-link").click()

Categories