Object [object HTMLAnchorElement] has no method 'attr' - javascript

I'm examining a DOM element using console.log. The DOM element is an anchor:
When I try to access its id and output it using either of the following lines:
console.log($this.attr(data-id));
or
console.log($this.data('id'));
I get an error:
Object [object HTMLAnchorElement] has no method 'attr'
('data' in the second case)
Does an anchor element not have the attr or data methods, or is my mistake something else?

That looks like its because your this reference is not a jquery object.
Try these instead:
$(this).data('id')
$(this).attr('data-id')

It is telling you exactly what the problem is. .data and .attr are jQuery functions. If your want to get an attribute value using a javascript object do the following, after giving an id to your element:
console.log(document.getElementById("a").getAttribute("data-id"));
jsFiddle: http://jsfiddle.net/hescano/pFdEj/

Something else is wrong in your page, then. The following does work:
$(this).data("id")
http://jsfiddle.net/RQw8E/
How are you using $(this)?

Works for me:
HTML
Click
JavaScript
$(".videoimage").click(function() {
var dataID = $(this).data("id");
var dataIDAttr = $(this).attr("data-id");
console.log(dataID);
console.log(dataIDAttr);
});
JSFiddle
Are you sure you attached some sort of event to the function that calls these statements?
You could also use vanilla JS
var anchorArr = document.getElementsByTagName("a");
for (var i = 0; i < anchorArr.length; i++) {
if(anchorArr[i].getAttribute("class")==="videoimage") {
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//quick and dirty, there are better ways to do this
console.log(anchorArr[i].getAttribute("data-id"));
}
}
jsFiddle

Related

jQuery - text() method?

Being fairly new to jquery and javascript I can't seem to understand how the .text() method really works. I read through the jQuery documentation but still can't figure it out.
for (var i=0; i < arrayLength; i++){
var currentElement = $(".artist")[i];
var currentArtist = currentElement.text;
console.log(currentElement);
console.log(currentArtist);
}
currentArtist returns "undefined" in the console. It works fine on the $(".artist") alone, but not when I use the [i] or anything additional for that matter. What am I missing here? How else could I grab a text value inside a selector?
By using the [] operator on jQuery object you're accessing the raw element node that was found by jQuery. This raw element doesn't have the jQuery methods anymore, nor a text property.
If you want to get single element from jQuery object and keep the jQuery wrapper, use eq method.
var artistElement = $(".artist").eq(i);
artistElement.text(); // gets the text content of the element
The code you've posted is also not very optimized. For instance, with every loop iteration you're searching the document over and over again for elements with class artist. Better to cache that search result in a variable before performing the loop. And if the loop iterates over all .artist elements, you can use jQuery's each method.
$(".artist").each(function () {
var artist = $(this); // this poits to the raw element thus wrapping into jQuery object
console.log(artist.text());
});
var currentArtist = currentElement.text;
Should be:
var currentArtist = currentElement.text();
You should use a each():
$(".artist").each(function(i,val){
var currentArtist = $(val).text();
console.log(val);
console.log(currentArtist);
});
$(".artist") produce a jQuery object that could be like this:
[div, div, div, div, prevObject: jQuery.fn.jQuery.init, context: document, selector: ".artist"...]
So the result of $(".artist")[i] is a HTMLElement and do not have a text method, that's why you're getting undefined
Also text() is a function and may be followed with ()
But if you want to keep the for loop you can do
for (var i=0; i < arrayLength; i++){
var currentElement = $(".artist")[i];
var currentArtist = $(currentElement).text();
console.log(currentElement);
console.log(currentArtist);
}
.text() shows the text of an html element or set of html elements that would be visible to the user.

jQuery throws an error that element.find() is not a function

I have written a small JS to iterate through a set of matched elements and perform some task on each of them.
Here is the code:
var eachProduct = $(".item");
eachProduct.each(function(index, element){
var eachProductContent = element.find(".product-meta").clone();
});
When I console log element it outputs properly and the exact objects. Why should jquery throw this error?
because element is a dom element not a jQuery object
var eachProductContent = $(element).find(".product-meta").clone();
Inside the each() handler you will get the dom element reference as the second parameter, not a jQuery object reference. So if you want to access any jQuery methods on the element then you need to get the elements jQuery wrapper object.
You are calling .find() on a plain JS object, But that function belongs to Jquery object
var eachProductContent = $(element).find(".product-meta").clone();
You can convert it to a jquery object by wrapping it inside $(). And in order to avoid this kind of discrepancies you can simply use $(this) reference instead of using other.
Use $(this) for current Element
var eachProductContent = $(this).find(".product-meta").clone();
you should change "element" to "this":
var eachProduct = $(".item");
eachProduct.each(function(index, element){
var eachProductContent = $(this).find(".product-meta").clone();
});

jQuery - console.log() returns an element but I can't access it

I happened to have super dumb issue and I'm stuck.
I do console.log(data) and I get exactly this:
<a href='http://www.someurl.com'>caption</a>
The question is how do I get this links "href" attribute.
I have absolutely no idea why, but these doesn't work:
data.text() == Uncaught TypeError: undefined is not a function (should be: caption)
$('a',data).attr('href') == undefined (should be: http://www.someurl.com)
Maybe this is not a string, but object or something else? How to check that? My JS looks like this:
window.send_to_editor = function(data) {
var videourl = data;
console.log(videourl.text()); // Uncaught TypeError: undefined is not a function
console.log(videourl); // <a href='http://www.someurl.com'>caption</a>
}
Using jQuery, you can do something like that:
var data = "<a href='http://www.someurl.com'>caption</a>";
var link = $(data).attr('href');
It will create dynamically your DOM element, then you will be able to get your attribute href.
You should first find out, what type data is. To do this you can use the JavaScript builtin function typeof(data).
It's not a jQuery object. That is why it is undefined. First, create a jQuery object.
var _videourl = $(videourl);
console.log(_videourl.text());
console.log(_videourl.attr('href'));
// caption (index)
// http://www.someurl.com
DEMO
In your case, data is a string, not a jQuery object and therefore does not have of jQuery's methods (like text).
If you are certain that data is a string containing a link, you can use a regular expression to extract the link like so:
var match = data.match(/href='(.*)'/g);
url = match && match[1];
console.log(url);
Alternately, you can create a jQuery object from your string. But that's a much more expensive operation if you just want to get the url.

jQuery this.html() returns undefined

I'm reformatting some really bad HTML using jQuery. I need to splice sibling <font> elements together. I tried this code:
$('font+font').each(function() {
this.html().appendTo( this.prev() );
this.remove();
});
but it gave me this error: TypeError: 'undefined' is not a function (evaluating 'this.html()')
Here's a sample of the HTML:
<font>This fragment </font><font>is actually one element.</font>
Update
I updated my code with $(this), but it still isn't working. When I run this code
$('font+font').each(function() {
$(this).html().appendTo( $(this).prev() );
$(this).remove();
});
I get this error: TypeError: 'undefined' is not a function (evaluating '$(this).html().appendTo( $(this).prev() )')
this has to be wrapped in a jQuery object, before you can use jQuery methods on it.
.html() returns a string. You cannot use jQuery methods on a string without wrapping. Use $this.prev().append( $this.html() ) instead.
When using $(this) more than once, it's wise to store $(this) in a temporary variable. It's the convention to prefix jQuery objects with a dollar sign.
Code:
$('font+font').each(function() {
var $this = $(this);
$this.prev().append( $this.html() );
$this.remove();
});
When you use an each statement, it returns this as a DOM element, not a jQuery object. .html() must be called on a jQuery object. So the first part of your fix is to convert this into a jQuery element with the $ symbol.
$(this).html(); //don't use this.html();
The second problem is that html() returns a string. You can't call AppendTo() on a string, only a jQuery object. Since you are working with .html() I'll assume that you want the string contents and not the full contents. If that were the case, Rob's answer is more appropriate.
this.textContent = $(this).prev().html() + this.textContent; // prepend siblings content
The final code ends up looking like this:
$('font+font').each(function() {
this.textContent = $(this).prev().html() + this.textContent;
$(this).prev().remove();
});
http://jsfiddle.net/b6vLL37k/1
You need to use $(this) not this
You need to use $(this) for jQuery to help you.
I wasn't able to fix your code. How about something like this:
var text = '';
$('font').each(function() {
text += $(this).text();
});
console.log($('<p />').text(text));

HTMLInputElement has no method 'val'

I'm looping through cells in a table row. each cell has a text box in it, and I want to take the value of the text box and push it onto an array.
function dothing() {
var tds = $('#'+selected+' td');
var submitvals = new Array();
tds.each(function(i) {
var val = $(this).children('input')[0].val();
submitvals.push(val);
});
}
Theres more to the function, but this is all that is relevant. For some reason, when I run this code, I get "HTMLInputElement has no method 'val'." I thought that input elements were supposed to have a val() method in jQuery that got the value so this makes no sense. Am I missing something, or doing it wrong?
val() is a jQuery method. .value is the DOM Element's property. Use [0].value or .eq(0).val()....
.val() is a jQuery function, not a javascript function. Therefore, change:
var val = $(this).children('input')[0].val()
To:
var val = $(this).children('input:eq(0)').val()
function dothing() {
var tds = $('#'+selected+' td');
var submitvals = new Array();
tds.each(function(i) {
var val = $($(this).children('input')[0]).val();
submitvals.push(val);
});
}
.val() is a jquery method. Using [0] returns the DOM element, not the jquery element
var val = $(this).children('input:first').val();
What I don't understand, is why none of the suggested syntaxes on this or other questions similar to this seem to work for me. I had to do trial and error and eventually had to use:
MySelectElement.value = x;
It also didn't help that the Visual Studio Intellisense suggestions offer a whole other range of unworking method names, such as ValueOf().

Categories

Resources