Get HREF value by class name - javascript

I'm trying to get href value of a specific anchor tag placed on a html page.
html tag structure
<a rel="nofollow" title="some title" href="http://www.this-is-what-i-need.com/just-this.html"><span><em class="buttonGo"></em>Go to this page</span></a>
How do I get the href value from above anchor tag using buttonGo class name?

A single line of plain Javascript will give you what you need:
var href = document.getElementsByClassName("buttonGo")[0].parentNode.parentNode.href;
But, if you aren’t sure how many times you need to use parentNode, you have to use a loop:
var anchor = document.getElementsByClassName("buttonGo")[0];
do{
anchor = anchor.parentNode;
} while(anchor.nodeName.toLowerCase() != "a");
var href = anchor.href;
Demo: Solution One (created by Milche Patern) and Solution Two

Using jQuery:
$('.buttonGo').closest('a').attr('href');
Without jQuery, you'll need to start with document.getElementsByClassName('buttonGo'), then crawl up parentElement until you find an a.
jQuery demo

If you want to get attribute of tag on which you are clicking, use:
$(this).attr("href");

Related

Javascript - meaning of `$("a[href*='video']")`

I have this line of code in which I can't explain to myself this $("a[href*='video']") line of code. There is just too much mystery in it.
$("a[href*='video']").click(function() {
var id = $(this).attr("href");
playVideo(id);
});
function playVideo(id) {
var $video = $(id + " video")[0];
$video.play();
$(".close").click(function() {
$video.pause();
$video.currentTime = 0;
});
}
$("a[href*='video']")
It's a jQuery attribute contains selector. This will return Array of all links <a> elements, whose href contains video in the link.
<a href="http://google.com/video/abc">
like this link contains video in url .. so, it will get selected.
What this selector does is first target all anchors, the bracket notation then targets an attribute of those elements. This could be class, id, value, href etc.
* is the wildcard selector
if you target * you're targeting everything within the document. Within this context you are targeting all anchors whose href includes the string 'video'.
The syntax looks crazy but it makes sense, it's a simple way to target every video link within your site.

Why link numbers are different?

I tried to count links within a page using JS, but got different results. Why there is a difference?
var intLNK = document.links.length;
console.log(intLNK);
var intA = document.getElementsByTagName("a").length;
console.log(intA);
Quoting from MDN
The links property returns a collection of all <area> elements and <a> elements in a document with a value for the href attribute.
document.getElementsByTagName("a").length;
will return the anchor elements irrespective of href attribute. You may use
document.querySelectorAll('a[href]').length
to get the number of anchors having href attribute.
If you're interested in performance of two see https://jsperf.com/document-links-vs-document-queryselectorall-aThanks to Robert Weber
document.links lists those a (and <area>) which have a href attribute, and your selector not - that's the difference.
More here (mdn)
Because some of the anchor a tag missing href attribute
A tag used for two purpose in HTML.
1) Tagging a location in a document.
<A Name = "Section1"> ... </A>
2) Making a hyperlink reference to another document or Tag.
< A HREF = "target location"> ... </A>
document.links.length will return count of Tags with HREF attribute, while document.getElementsByTagName("a").length will return count of all A tags no matter link or Not.
That's why the output is different.
It's because firsts you're looking for all href values but later your looking for all anchor tags. That's why the results are different
If you want to get all the anchor tags with an href in it you can do it with jquery like this
$('a[href]').length

Why I can not change the href value by jQuery?

Below is my code..
var content = $("XXXX");
content.find("a").each(function() {
var value = $(this).attr('href');
$(this).attr('href', encodeURI(value));
alert(value);
});​
However, it keep showing error.
How can I make this code work which I want to encode the url.
Instead of content.find('a') use content.filter('a'). Because right now you're content is an array of only one element (ie. <a>), so there is no more <a> within that <a> and .find('a') fails here.
So .filter() is safe to use.
Demo
No need to use JQuery.find here as content variable has only anchor tag and you want to apply encodeURI for your URL.
For that requirement below code is well enough.
$(content).each(function(){
var value = $(this).attr('href');
$(this).attr('href', encodeURI(value));
alert($(this).attr('href'));
}
);
Hope it helps you.
maybe you should add an ID (if you want to use this for more than one element then create a specific class for the elements and link via $(".classname")) to your link and then use a normal query like this
var yourLink = $("#yourID");
yourLink.attr('href', encodeURI(value));​
and make sure that your value has something in it. Also if .attr(...) has still no effect please try .prop("href", encodeURI(value))

Add target attribute to anchor tags without id or class

I've got an input which allows users to add text with anchor tags for hyperlinks. I'd like to keep it simple for the user so all they need to enter is link but would love to add a target attribute to the tag systematically.
Is there an elegant way in JavaScript I can do this without having an ID associated with the tag? (e.g. getElementById wont work here). Other entries I found in stackoverflow address this but only when the anchor tag has an ID.
These links will, however, always have the same parent div class.
Found a JavaScript-only way to accomplish this:
var nLink = $("div.notification-popup-message > a");
nLink.click(function(e) {
e.preventDefault();
window.open(this.href);
});
Another method using querySelecterAll that actually adds the attribute to the HTML in the DOM:
var messageLink = document.querySelectorAll("div.message > a");
$(function() {
$(messageLink).attr("target", "_blank");
});

Is it possible to grab a link by its href if it doesn't have a class or ID?

I'm using someone else's app and want to change the innerHTML in between any < a>< /a> tag that has a certain href. But these links don't have a class or ID associated with them and I can't edit the code to give them classes or ID's. Is there a way to grab a tag by its href in JavaScript? I wanted to do something similar to this:
var theLink = document.getElementByHref("example.com");
Otherwise, if that is not possible, can I loop through all the links in the page and choose the ones that have the certain href and innerHTML I'm looking for?
You can use a DOM3-attribute-selector (jQuery doc) to get all elements that contain a certain text in their href attribute. It would look like
$('a[href*="example.com"]')
However, that might not be what you actually want - not only urls to that domain might contain this string. You might do something like begins-with:
$('a[href^="http://example.com"]')
but to get an exact and possibly more complex match, you don't get around a custom filter:
$('a[href]').filter( function() {
return this.hostname == "example.com";
// or check other properties of the anchor element
})
Select all elements that have the example.com value in href attribute:
Live Demo: http://jsfiddle.net/NTGQz/
$('a[href*="example.com"]');
You can also try this, just to be more specific and following the OP "ideal" answer:
Live Demo: http://jsfiddle.net/ksZhZ/
jQuery.fn.getElementsByHref = function(str){ return $('a[href*="' + str + '"]'); };
$(document).ready(function(){
elems = $(this).getElementsByHref('example.com');
});
jQuery has a lot of selectors. The one you want here is the attribute selector.
$('a[href="example.com"')
You can use an attribute selector:
$('a[href="http://example.com"]')
With JQuery attribute selector, you can do this :
$('a[href="example.com"]')
Try this
$('a[href*="example.com"]');
This will select the link that has example.com in the href attribute..
$('a[href="http:google.com"]')
you can do it with jquery: http://api.jquery.com/attribute-equals-selector/
ex: linksToGoogle = $('a[href="http://google.com"]');
You can do this without jQuery.
var links = document.querySelectorAll('a[href*="example.com"]');
You can do this natively with querySelectorAll if your users are on IE8+ or any other browser. This method returns an NodeList of matching elements.
document.querySelectorAll('a[href="exact/value.html"]'); // exact match
document.querySelectorAll('a[href*="partial/value.html"]'); // partial match
document.querySelectorAll('a[href^="starts/with"]'); // href starts with
document.querySelectorAll('a[href$=".html"]'); // href ends with

Categories

Resources