0

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.

1
  • <div class="wrapper"></div> Commented Jun 17, 2017 at 16:43

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah stringify works. But how to add another name/value to what we just added? I'm building the array on each event. The next one replaces what we added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.