I am trying to check if an object with class sourceFocus has data in it. However when I check it, it does not have data when it should. What am I doing wrong here?
$('.source').click(function() {
$('.source').removeClass('sourceFocus');
$(this).addClass('sourceFocus');
$(this).data('source_selected', true);
console.log($.hasData(this));
console.log(this);
});
$('.target').click(function() {
$('.target').removeClass('targetFocus');
$(this).addClass('targetFocus');
$(this).data('target_used', true);
//$('.sourceFocus').data('source_used', true);
console.log($.hasData('.sourceFocus'));
if($.hasData('.sourceFocus')){
console.log("has data worked");
check_for_duplicates();
}
I am trying to check if an object with class sourceFocus has data in it. However when I check it, it does not have data when it should. What am I doing wrong here?
$('.source').click(function() {
$('.source').removeClass('sourceFocus');
$(this).addClass('sourceFocus');
$(this).data('source_selected', true);
console.log($.hasData(this));
console.log(this);
});
$('.target').click(function() {
$('.target').removeClass('targetFocus');
$(this).addClass('targetFocus');
$(this).data('target_used', true);
//$('.sourceFocus').data('source_used', true);
console.log($.hasData('.sourceFocus'));
if($.hasData('.sourceFocus')){
console.log("has data worked");
check_for_duplicates();
}
Share
Improve this question
asked Aug 23, 2011 at 18:14
RATaboraRATabora
3935 silver badges10 bronze badges
2
- Can you paste the HTML also, want to know see where you assigning the class sourceFocus and do you want read the HTML between the tags for which you using the sourceFocus class – Safran Ali Commented Aug 23, 2011 at 18:33
-
You can also check if the returned data value is undefined
$obj.data('hello') !== undefined
– KyleMit ♦ Commented Nov 28, 2017 at 14:49
3 Answers
Reset to default 3I don't think the .hasData()
method accepts selectors in your case .sourceFocus
, try selecting .sourcefocus
as an element and then passing that to the .hasData()
function.
try something like...
console.log($.hasData($('.sourceFocus:first')));
$.hasData() checks against a DOM Element you have to get it out of the jQuery object, either using array notation or the .get() method (not to be confused with the $.get() ajax method)
console.log($.hasData($('.sourceFocus')[0]));
If you trying to read the HTML between the tags for which you are using .sourceFocus class then do this in your if statement:
$.hasData($('.sourceFocus').html())