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

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.

Related

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

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");
});

Get HREF value by class name

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");

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

Specify jquery selector using variable

I can't get $(target) to work.
If I click on a link with href=#top, alert(target) displays #top, but $(target).offset returns null.
$("[href^='#']").click( function() {
var target = $(this).attr('href');
alert(target);
$("#body-wrapper").animate( {scrollTop: $(target).offset().top} ,300);
return false
})
};
When you do:
$(target).offset()
You're essentially doing:
$("#top").offset()
But, you apparently don't have an object in your page with an ID of "top" (thus why it returns null). So, this could work if you gave the link with the name of top that ID also like this:
<a name="top" id="top"></a>
Or, instead, you could use this jQuery to look for the link tag with name="top":
target = target.slice(1); // remove # from start of the name
$("[name='" + target + "']").offset() // construct $("[name='top']");
Here you look for a tag with an attribute of name='top'.
Use $(this).offset(). Your target var is just a string, not a jQuery object or a DOM node.
May be the element #top does not exist on the page. Try to alert $(target).length and see what you get.

Categories

Resources