Getting data- attributes using jQuery - javascript

A <img /> element has a data-id attribute that I want to retrieve using jQuery. I believe the .data() function can do this.
$('.photo').get(0).data('id')
Problem: When I tried using .data('id') to retrieve the attribute, I get the error:
Uncaught TypeError: Object #<HTMLImageElement> has no method 'data'
Where did I go wrong?
jsfiddle: http://jsfiddle.net/KLG3R/

like others said, your problem is the .get(0) which returns the HTML element itself, rather than a jquery object. To get a certain element, you use the :eq pseudo selector like:
http://jsfiddle.net/gunderson/KLG3R/2/
$('#result').html( $('.photo:eq(0)').data('id') );

You need to use data to a jquery object and get(0) will return the element.
$('#result').html( $('.photo').data('id') );
Check the below fiddle
http://jsfiddle.net/KLG3R/1/

$('.photo').get(0) will return the HTMLImageElement, not the jQuery object, so it doesn't have a method .data.
You should just do with: $('.photo').data('id')

use .attr() function. Like
$('#result').html( $('.photo').attr('data-id') );

Your using jQuery .get() you need to use .eq() in this case. Also your using .data() which is used to store data on the dom. You need to be using .attr() which gives you access to the attributes of the element.
$(function () {
var photos = $('.photo');
$('#result').html(photos.eq(0).attr('data-id'));
});
This should be working for you now: http://jsfiddle.net/KLG3R/4/

There are two types of an element. That is DOM object and jQuery object;
jQuery object has data() method, while DOM object like your xx..get(0) has no method data();
So, if you want to use data() method, you must ensure the object is jQuery object.

Related

Error: Object doesn't support property or method 'css'

I have multiple objects with the classname "level1" (this is built on asp.net, the element does not allow setting an ID here)
What I am trying to do is get one of them and assign css properties
$(".level1")[1].css({"background-color":"yellow"});
I get the error
Error: Object doesn't support property or method 'css'
When I do this:
console.log($(".level1")[1].innerHTML);
I get the correct innerHTML, so I know it gets the right element
Use eq:
$(".level1").eq(1).css({
"background-color": "yellow"
});
$(".level1")[1] returns the HTML and not the jQuery Object, so you cannot call jQuery method on it. Use eq instead.
eq(1) will get the Second element having class level1(Index starts from 0)
Docs: http://api.jquery.com/eq/
Reduce the set of matched elements to the one at the specified index.
$(selector)[1] gets the DOM element. To manipulate it again you need the jQuery object:
$($('.level1')[1]).css('background-color', 'yellow');
Edit - see Tushar's answer using .eq()
Make from $(".level1")[1] a jQuery object, because [1] returns HTML DOM element and you need jQuery object for .css() method.
$($(".level1")[1]).css({
"background-color":"yellow"
});

addClass to element inside an array

can you help me understand why this is not working?
var elementTab1 = $('#tab1 .item-media.modificato');
elementTab1[0].addClass('selezionato');
this through this error
TypeError: undefined is not a function (evaluating 'elementTab1[0].addClass('selezionato')')
Thanks
elementTab1 is already a jQuery object. It contains an array of matched elements in the DOM. Accessing the first index using [0] will return a native element with access to the native JavaScript API (and not jQuery's).
jQuery does provide a nice way to grab items from the array though. It is .eq().
elementTab1.eq(0).addClass('selezionato');
Accessing an element of a JQuery object (via your elementTab1[0]) call returns the DOM element, not a JQuery element.
DOM elements do not have an .addClass method.
The following code should work for you:
$(elementTab1[0]).addClass(".selezionato");
Alternately, just skip JQuery and use the native DOM APIs:
document
.querySelector("#tab1 .item-media.modificato")
.classList
.add(".selezionato");

getAttribute method with jquery object

I am using filter to return a particular element. I want to know why .getAttribute is not working with returned object while it is working fine with .attr(). jsfiddle
var c = $('ul li').filter(function(){
if($(this).text()=='d')
return this;
});
console.log(c.getAttribute('value'));
You are mixing javascript with jquery. getAttribute is a javascript function.
try this
console.log(c.attr('value'))
Or simple
console.log(c.val())
.getAttribute() is a method associated with DOM object not with with jQuery object.
If you want to use it you need to get DOM object like
console.log(c[0].getAttribute('value'))
or
console.log(c.get(0).getAttribute('value'))
var c is array object and not single object. Use index like below :
console.log(c[0].getAttribute('value'))
^--- 0 index
JSFiddle

jQuery in console not working properly

I'm using the jQueryify bookmarklet on a page so that I can call jQuery functions from the console. But everytime I invoke a jQuery function on a selected object, I get the error:
"TypeError: jQuery("li")[0].children[0].html is not a function
[Break On This Error] jQuery('li')[0].children[0].html();
I have tried this in FireBug as well as Google Chrome's Webkit console.
You are no longer working with jQuery objects when using square braces.
jQuery("li")[0]
This returns you the 1st li as a DOMElement, not a jQuery object.
jQuery("li")[0].children[0]
This returns the 1st li's 1st child as a DOMElement, not a jQuery object.
.html()
This function only works for jQuery objects. For DOMElements, you can use the .innerHTML property.
I suggest instead of dealing with DOMElements, you should continue working with jQuery objects. Try using this instead:
jQuery('li').eq(0).children().eq(0).html()
It looks like you are trying to call a jQuery function, html, on a DOM object children[0]. Try wrapping that in a jQuery object and then calling html
var temp = jQuery("li")[0].children[0];
var html = jQuery(temp).html();
Check the result of jQuery("li")[0].children[0] , it's a regular DOM object NOT a jQuery object. Without seeing your HTML i can't recommend a better selector but a cheap and dirty fix would be
jQuery(jQuery('li')[0].children[0]).html();
This will convert the DOM object result into a jQuery object which has the .html() function.
Accessing the array elements on the jquery object (using []) returns a DOMElement, which obviously doesn't have jquery's methods. You probably want to use eq() instead.
Try following
jQuery(jQuery("li")[0].children[0]).html();
or better one
jQuery("li:eq(0)").children(':eq(0)').html();
or another one
jQuery("li:eq(0)").children().eq(0).html();
even this one will work
jQuery("li").eq(0).children().eq(0).html();

JQuery select by ID vs document.GetElementByID

I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of a JQuery selector. Just wondering why the javascript getElementById below works fine when passing an object to a function, but the second one doesn't?
Thanks!
// works
addTask(document.getElementById('taskText'), evt);
// doesn't
addTask($('#taskText'), evt);
getElementById() returns a DOM element reference.
jQuery's selector returns a jQuery object. You can get the element reference from the jQuery object using
$('#taskText').get(0);
See http://api.jquery.com/get/
To add to the other answer, regarding the result, if you want to use jQuery (which is easier to read), you can get the dom node directly like so:
addTask($('#taskText')[0], evt);
$('#taskText') returns a jQuery object reference.
document.getElementById('taskText') returns a DOM element reference.
If your addTask() function doesn't know how to convert them to what it needs, then that would be the issue since one of them will need a conversion.
If you want to get the first DOM element reference from the jQuery object, you can do so with this:
$('#taskText').get(0)
So these two should be identical:
$('#taskText').get(0)
document.getElementById('taskText')
Both are not exactly same
document.getElementById('taskText'); //returns a HTML DOM Object
var contents = $('#taskText'); //returns a jQuery Object
var contents = $('#taskText')[0]; //returns a HTML DOM Object
so you have to change it to get HTML Dom Object
addTask($('#taskText')[0], evt);
As #Phil and #jfriend00 have pointed out, document.getElementById('taskText') is a DOM element, and $('#taskText') is a jQuery object. The latter is an object of all DOM elements that match the selector.
Think of it as a zero based array, you could pass in the DOM element by doing this:
addTask($('#taskText')[0], evt);

Categories

Resources