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.
Related
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.
I have a CSS rule for hiding elements with a class="hidden" and I'm using jQuery to toggle this class on and off on whatever ID i click on so I can make elements disappear.
Why does this not work?
$(this).attr('id').toggleClass("hidden");
but this does?
var x = "#" + $(this).attr('id');
$(x).toggleClass("hidden");
I know that the id is being taken correctly on the first example, but it seems that to toggle the class I have to add a "#". I haven't seen any examples of others having to resort to this so I'm wondering what madness I have here.
Many thanks
$(this).attr('id').toggleClass("hidden");
You are chaining events here. $(this).attr('id') already returns you a string. So you are technically doing "someid".toggleClass("hidden") which doesn't makes sense.
In your second example, you are actually selecting the same element again via id and firing your method, which is right
.attr('id') returns a string, not an element.
Let's pretend your element has an ID of myThing. Here's what your code translates to:
// 1
"myThing".toggleClass("hidden");
// 2
var x = "#myThing";
$("#myThing").toggleClass('hidden');
But really, if you're getting the ID from this, there's no reason to extract the ID in the first place. Just use this directly.
$(this).toggleClass('hidden');
You can simply use:
$(this).toggleClass("hidden");
$(this) is the actual element you're working with, so you can use this to directly toggle classes with.
In your examples, $(this).attr('id') is a string, and not an element.
This code works, because you're taking the ID (As a string), and selecting the ID on the webpage.:
//Store the id into a string
var x = "#" + $(this).attr('id');
//Pass the ID back into jQuery, and find the element
$(x).toggleClass("hidden");
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))
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
I have a link:
MyLink
What I need to do with jQuery to edit the href attribute?
If you want to modify the displayed anchor text, use .text()
$('a').text(function(_, currentText) {
return 'Here ' + text
});
That would change the line into
Here MyLink
If you want to modify the linked href, use .attr()
$('a').attr('href', 'your new value');
You can use the .attr() the same way I demonstrated with .text() above (passing a function and access the current value also)
Ref.: .attr(), .text()
Easy
$('a').attr('href','yourTextHere');
Yes
$("a").attr('href', 'value');
Might be a good idea to set an ID on the element to specifically target it:
$("a#id").attr('href', 'value');
This should do it.
$("#id").attr("href", "Etc");
.attr()
First add a class name to that link, as shown below.
MyLink
Then,
$('.classname').attr('href','insert link here');
If you're wanting to change the text of the link then:
$('a').text('My link text');
If it's the href you want to change, then, as noted by others it's:
$('a').attr('href','newURL');
If you're okay using plain JavaScript:
var a = document.getElementById('aElementID');
a.innerHTML = 'My Link Text';
a.href = 'http://new.link.com/path/to/page.html';
Note that you'll need some way to uniquely identify the particular a element you want to target, either using an id (to give $('#aElementID')) or a class (to give $('a.className'), though this will return a node list/array of elements that you'll then have to iterate through).
you can attach it as by specifying the id to it and then uniquely accessing the anchor tag by the classname
;
$("a.mylink").attr('href', 'http://google.com');