user300979
user300979

Reputation: 437

Add name and value to data attribute array with attr()

I'm trying to build and array inside a data attribute but I'm getting [object, object] when I try to add the name and value

<div class="wrapper"></div>

$post_url = "http://example.ai";
$post_id = "750";
$(".wrapper").attr("data-history", {
  id: $post_id,
  url: $post_url
});

I'm first creating the data attribute "history" but then it adds [object, object] to it. After this I need to add another name/value to the "history" array on the next event.

Upvotes: 0

Views: 944

Answers (1)

Musa
Musa

Reputation: 97717

Two issues, one is that you should not have the dot(.) in the class attribute and two you have to add the attribute as JSON (or use .data, depending on how you want to use the attribute)

<div class="wrapper"></div>

$post_url = "http://example.ai";
$post_id = "750";
$(".wrapper").attr("data-history", JSON.strinify({
  id: $post_id,
  url: $post_url
}));

or

$post_url = "http://example.ai";
$post_id = "750";
$(".wrapper").data("history", {
  id: $post_id,
  url: $post_url
});

EDIT:

To add new items just get the old data and add the new data to it

$post_url = "http://example.ai";
$post_id = "750";
var data = $(".wrapper").attr("data-history");
if (!data){
    data = [];
}
else{
    data = JSON.parse(data);
}
data.push({
  id: $post_id,
  url: $post_url
});
$(".wrapper").attr("data-history", JSON.strinify(data));

or

$post_url = "http://example.ai";
$post_id = "750";
var data = $(".wrapper").data("history");
if (!data){
    data = [{
        id: $post_id,
        url: $post_url
    }];
}
else{
    data.push({
        id: $post_id,
        url: $post_url
    });
}    
$(".wrapper").data("history", data);

Upvotes: 2

Related Questions