Setting href attribute at runtime - javascript

What is the best way to set the href attribute of the <a> tag at run time using jQuery?
Also, how do you get the value of the href attribute of the <a> tag using jQuery?

To get or set an attribute of an HTML element, you can use the element.attr() function in jQuery.
To get the href attribute, use the following code:
var a_href = $('selector').attr('href');
To set the href attribute, use the following code:
$('selector').attr('href','http://example.com');
In both cases, please use the appropriate selector. If you have set the class for the anchor element, use '.class-name' and if you have set the id for the anchor element, use '#element-id'.

In jQuery 1.6+ it's better to use:
$(selector).prop('href',"http://www...") to set the value, and
$(selector).prop('href') to get the value
In short, .prop gets and sets values on the DOM object, and .attr gets and sets values in the HTML. This makes .prop a little faster and possibly more reliable in some contexts.

Set the href attribute with
$(selector).attr('href', 'url_goes_here');
and read it using
$(selector).attr('href');
Where "selector" is any valid jQuery selector for your <a> element (".myClass" or "#myId" to name the most simple ones).
Hope this helps !

Small performance test comparision for three solutions:
$(".link").prop('href',"https://example.com")
$(".link").attr('href',"https://example.com")
document.querySelector(".link").href="https://example.com";
Here you can perform test by yourself https://jsperf.com/a-href-js-change
We can read href values in following ways
let href = $(selector).prop('href');
let href = $(selector).attr('href');
let href = document.querySelector(".link").href;
Here you can perform test by yourself https://jsperf.com/a-href-js-read

<style>
a:hover {
cursor:pointer;
}
</style>
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".link").click(function(){
var href = $(this).attr("href").split("#");
$(".results").text(href[1]);
})
})
</script>
<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>
<br /><br />
<div class="results"></div>

Related

How to set span value inside of anchor tag

I have anchor tag in which some class bind dynamically on page load, I need to change the value of span tag inside anchor tag below is my code:
<a id="aView" km-button km-state-active" data-badge="0" href="#view" data- icon="globe" data-role="tab">
<span class="km-icon km-globe"></span>
<span class="km-badge">0</span>
<span class="km-text">view</span>
</a>
I need to change "km-badge" value using JavaScript or jQuery need help
$("#aView .km-badge").text("blablabla");
2nd:
var el = $("#aView .km-badge"); // define variable that points to DOM object
el.removeClass("km-badge"); // remove class from object
el.text("blablabla"); // change attribute "text" of object
el.addClass("km-badge"); // add class to object
with javascript you can do,
<body>
<script type="text/javascript">
document.getElementById("aView").innerHTML = "writetexthere";
</script>
</body>

How to get value from a tag

I have a link like this
<a id="idPage" href="#">${currentPage}</a>
and in this case I can get value from tag doing this way
$(this).text();
now let's the link will be like this
<a id="idPage" href="#">next page</a>
<!-- the value of ${currentPage} still must to be available for a script-->
How to pass the value and how to get in script in this case?
An appropriate way to do this would be to use a data attribute and jQuery's $.data method like so.
<a id="idPage" href="#" data-currentpage="${currentPage}">next page</a>
And then to access that value,
$("#idPage").data('currentpage')
The simple solution is to store the value in a variable
jQuery
var tagValue = $("#idPage").text();
JavaScript
var tagValue = document.getElementById("idPage").innerHTML;
but it's probably the best idea to use HTML5 data attributes as mentioned in the comments.

Javascript - having trouble selecting an id

I gave my link a an id where if I click the link, I want my javascript to adjust the background image. I made a js-fiddle of a simple version of what I want here:
https://jsfiddle.net/qp8d390b/
<body background="http://www.blueskiescareers.co.uk/wp-content/uploads/2014/05/blue-sky-clouds.jpg">
<li>
<a id = "attempt1" href="#top">SNOOPY1</a>
</li>
<li>
<a>SNOOPY2</a>
</li>
<li>
<a>SNOOPY2</a>
</li>
<div id= "#top">TOP PART </div>
</body>
$(document).ready(function() {
$("a[id='attempt1']").click(function(e) {
e.preventDefault();
alert('works');
document.body.background = "https://upload.wikimedia.org/wikipedia/commons/0/02/Fried_egg,_sunny_side_up.jpg";
});
});
I'm new to selecting with javascript. Any help would be appreciated!
try to use $("#attempt1")
use # to get any id in html
Firstly your HTML is invalid; li must be in either a ul or ol and all a elements must have either a name or href attribute.
Secondly, jQuery uses CSS rules, so to select by id is $('#attempt1').
Lastly, to change the background CSS property to an image the URL string should be wrapped in url(). Try this:
$(document).ready(function() {
$("#attempt1").click(function(e) {
e.preventDefault();
$('body').css('background', 'url("https://upload.wikimedia.org/wikipedia/commons/0/02/Fried_egg,_sunny_side_up.jpg")');
});
});
You can select it with :
$('#attempt1')
You should use id-selector in this case
https://api.jquery.com/id-selector/
$("#attempt1")
The selector you used which is attribute selector is more used in inputs than in links (a elements)
https://api.jquery.com/attribute-equals-selector/
You can find more info on jQuery selectors in
https://api.jquery.com/category/selectors/
Hope it helps

on dom ready remove existing html attribute and add mine

My generated portion of page source is
<a target="_blank" href="/img/image001.png">
<img width="286" height="171" alt="" src="/img/image001.png">
</a>
and I need on page load to replace this a target with a rel so above link should be
<a rel="lightbox" href="/img/image001.png">
<img width="286" height="171" alt="" src="/img/image001.png">
</a>
I trid with after </body>
<script>
$(function() {
$('a[_blank]').removeAttr('_blank').attr("rel=","lightbox");
});
</script>
You need to use the attribute equals selector - you need to use the attribute name along with attribute value, also to remove you need to use the attribute name not value.
$('a[target="_blank"]').removeAttr('target').attr("rel","lightbox");
Your code looks for an anchor element with attribute _blank and then removes it, a anchor element like <a _blank href="/img/image001.png">
Also as #PaulDraper suggested move the script inside the body element
$(document).ready({
$('a[target=_blank]').attr('rel', 'lightbox');
})

html anchor tag reference

i have an anchor tag as below.
<a style="border:0px" href='javascript:deleteAttachment(this);' />
Inside the deleteAttachment, how can i get the anchor tag. Sending this to the method, sends the window element to the method.
function deleteAttachment(ancElement){
//Jquery operation on acnElement
}
Please helop me out.
I would recommend a slightly different approach, since what you're trying to do is a bit old.
assuming you already loaded jQuery, here we go:
<a id="myFirstLink" href="someHref" />
<a class="otherLinks" href="secondHref" />
<a class="otherLinks" href="thirdHref" />
<script>
$(function() {
$('#myFirstLink, .otherLinks').click( function(event) {
// stops the browser from following the link like it would normally would
event.preventDefault();
// do something with your href value for example
alert( $(this).attr('href') );
});
});
</script>
So basically what you can do is this: simply generate all your anchors like you would normally would and apply the same class name to each of them - in my example the class would be "otherLinks".
After that, all your links will be handled by that anonymous function.
Use the onclick handler:
<a onclick="deleteAttachment(this)">
or, the cleanest and most accepted method nowadays, have just the raw link in the HTML:
<a id="deleteAttachment">
and add the click event programmatically, in a separate script block, on DOM load:
document.getElementByID("deleteAttachment").onclick =
function() { ... you can use "this" here .... }
you must set its ID attribute
<a id="myAnchor" style="border:0px;" href="javascript:deleteAttachment('myAnchor');"/>
then use jquery to find it
function deleteAttachment(ID)
{
var MyAnchor = $('#'+ID);
}

Categories

Resources