Run
Run

Reputation: 57256

jquery.data: How to store a data to an element and access it?

How can I store a data to an element and then manipulate that check if it has the data?

For instance I have these two elements with the same class name.

<div class="elem"></div>
<div class="elem"></div>

jquery,

$(".elem:first").data("hasdata","popup");

if($(".elem").data("hasdata") === 'popup') $(".elem").css({background:'red'})

I get two red but I just want the first one to turn red. Is it possible?

my test on jsfiddle

Upvotes: 0

Views: 78

Answers (3)

tomatentobi
tomatentobi

Reputation: 3157

You can use each to iterate over all elements with the class elem

$(".elem:first").data("hasdata","popup");
$(".elem").each(function(){
  if ($(this).data("hasdata") === 'popup'){
    $(this).css({background:'red'});
  }
});

check this jsFiddle

Upvotes: 2

Adil
Adil

Reputation: 148150

You can use filter() and put condition in it.

Live Demo

$(".elem:first").data("hasdata","popup");
$(".elem").filter(function(){
    return $(this).data("hasdata");
}).css({background:'red'});

Upvotes: 2

user1
user1

Reputation: 1065

try this:

$(".elem:first").attr("data-hasdata","popup");

$(".elem[data-hasdata='popup']").css({background:'red'});

JSfiddle Demo

Upvotes: 2

Related Questions