The following code this not work, because attr is undefined:
$("#foo a[href]").each(function()
{
this.attr("href", "www.google");
});
But this code does:
$("#foo a[href]").each(function()
{
this.href = "www.google";
});
Why??
The following code this not work, because attr is undefined:
$("#foo a[href]").each(function()
{
this.attr("href", "www.google.");
});
But this code does:
$("#foo a[href]").each(function()
{
this.href = "www.google.";
});
Why??
Share Improve this question asked Jul 27, 2011 at 13:26 MattMatt 2,6441 gold badge16 silver badges19 bronze badges 1-
Fyi, a link to
www.google.
will not do what you want. You needhttp://
in front of it. Unless you have a file namedwww.google.
in the same folder as your html file of course ;) – ThiefMaster Commented Mar 3, 2012 at 20:52
7 Answers
Reset to default 10You need to wrap this
... $(this)
attr
is a method of a jQuery object, href
is a property of an element node
The this
reference in your function is a reference to a DOM element. The reference is not a jQuery object.
Because this
inside an each refers to the DOM element itself rather than the jQuery version of it, and the attr
method is only defined on the jQuery object.
So, to use the attr
method you need to wrap the DOM element in a jQuery object:
$("#foo a[href]").each(function()
{
$(this).attr("href", "www.google.");
});
try .prop()
this.prop("href", "www.google.");
$("#foo a[href]").each(function()
{
$(this).attr("href", "www.google.");
});
You need the $()
Because this
isn't a jQuery object.
Try:
$("#foo a[href]").each(function() {
$(this).attr("href", "www.google.");
});
Did you mean this instead?
$(this).attr("href","www.google.");
?