Why I can not change the href value by jQuery? - javascript

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

Related

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

jQuery '#' + data("target") pattern

I've seen this a bunch:
Click me
<div id="content">And something will happen here</div>
With JS like this:
$("#trigger").click(function(){
$("#" + $(this).data("target")).hide();
})
It looks a little weird to me to be doing this string concatenation to create selectors which are then used to get the target element. Is there a better pattern in Javascript (with jQuery available) for setting up handlers on one element which need to know about another target element?
Why you do string concatenation just store the id with #
Click me
$("#trigger").click(function(){
$($(this).data("target")).hide();
})
Similarly you can store any selectors as is in data-target say for ex:- .tab1 etc so that you do not have to perform string concatenation again inside the click or any event.
You can simply use
$('#content').modal('toggle');
Any where in you're code to initiate the modal show and hide,
You can use even "show"/"hide" functionality directly.
I assume you're using Bootstrap and one of the latest versions of jQuery.
Enjoy !
Why not do something like this, a much better approach in my opinion:
// Set the target
$("#trigger").data('target', $('#content'));
// Get the target
$("#trigger").click(function(){
$(this).data("target").hide();
})
If you're setting it from the backend, I would include the hash with the attribute value as others have suggested.
Click me
$("#trigger").click(function(){
var target = $(this).data("target");
$(target).hide();
})
You always have the option to build the selector, looks a bit nicer than concatenating the string inside the selector.
$("#trigger").click(function(){
var selector = "#" + $(this).data("target");
$(selector).hide();
});
A little nicer, not sure if it's what you're looking for.
I would skip the data- completely, thus allowing graceful degradation.
Click me
<div id="content">And something will happen here</div>
with
$("#trigger").click(function(e){
e.preventDefault();
$( $(this).attr("href") ).show();
// note, i'm purposly not using this.href due to a bug in IE that would return the entire href rather than just the hash
})
$(this).attr('data-target', '#myTarget');
this worked for me

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

How can I alter the `href` attribute of an anchor using jQuery

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

jquery- store id of clicked link in variable

This should be basic, but for some reason its not working for me. I just want to store the id when a link that has a certain class is clicked in a variable so as an example:
Some link
I would want jquery to get the id of the link above and store it in a variable. I have tried $this.attr("id") and $this.id, but non of this worked.
This is what I have for the jquery:
$(".only_this_class").click(function() {
var clickedId= $(this).attr("id");
alert(clickedId);
});
I just get "undefined" every time.
I removed the space between this and _class in class="only_this _class" and it is working for me.
Try this here
Please have a look at jQuery Selectors
If you have two classes in your HTML then the syntax is different:
$('.classA.classB')
Have a look at How can I select an element with multiple classes?
NAVEED is right, if you remove the space it works, because if there is a space HTML will put two classes on the element: only_this and _class.
If you are in fact looking for two different classes, you should replace the space with a dot to make it work properly, as in $(".only_this._class")
$(".only_this _class") this selector will look for _class tag in .only_this element. May you are looking for $(".only_this") which will select element which has this class. Try this.
$(".only_this").click(function() {
var clickedId= $(this).attr("id");
alert(clickedId);
});

Categories

Resources