简体   繁体   中英

How can I get a data attribute from an array into an h3 on the DOM using js / jquery?

I have a var that has some data attributes in it.

var test = {
  "game": [
    {
      "Title": "blah",
      "Type": "Sports"
    }
  ]
}

I am trying to populate the Title in a h3 on the DOM. This is what I am currently trying to use:

$(function(){
  $('#currentGame').val(test.game[0].Title);
});

When I do this I don't get an error but nothing shows up on the page. The #currentGame is the id of the h3.

.val() is usually used for form elements like input. You will want to use .text() for escaped text or .html() for html

Assuming your page contains an H3#currentGame and you want to set its 'title' attribute, you can

$(function(){
  $('#currentGame').attr('title',test.game[0].Title);
});

On the other hand, if you only wish to set the HTML content of the H3, the text between the <H3> and </H3>, you'd use: $('#currentGame').html(test.game[0].Title);

Or $('#currentGame').text(test.game[0].Title); if the value of your title is never expected to contain any HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM