bona
bona

Reputation: 45

get custom attribute value with jquery

Trying to get attribute value with jQuery, then append it to element with class

<div id="data" class="democlass" data-author="Mr. Jhon Doe" data-cat="Technology" data-url="https://google.com"></div>

<p class="data-author"></p>
<p class="data-cat"></p>
<a href="#"></a>
$("#data").each(function() {
    var author = $(this).attr("data-author");
    var cat = $(this).attr("data-cat");
});

$( document ).ready(function() {
    $( ".data-author" ).append(author);
    $( ".data-cat" ).append(cat);
});

Am I doing something wrong in the code? here is the sample codepen

Upvotes: 0

Views: 2390

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115272

Variables are in different scope so it will be undefined, so do both actions within the document ready handler. Although each() is completely unnecessary here since id is unique(if there are multiple elements with same id then only the first element get selected).

$(document).ready(function() {
  // cache the element
  var $ele = $("#data");

  // append contents
  $( ".data-author" ).append($ele.attr("data-author"));
  $( ".data-cat" ).append($ele.attr("data-cat"));
});

UPDATE : You although use data() method to get custom data-* attribute value.

$( ".data-author" ).append($ele.data("author"));
$( ".data-cat" ).append($ele.data("cat"));

Upvotes: 2

Owais Aslam
Owais Aslam

Reputation: 1589

No need for each loop

$( document ).ready(function() { 
$( ".data-author" ).append($("#data").attr("data-author"));
$( ".data-cat" ).append($("#data").attr("data-cat"));
});

Upvotes: 0

Related Questions