0

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

5
  • 1
    variable in different scope Commented Jan 22, 2017 at 14:25
  • first why you are using each on id attribute ? and i didn't find more than one div to use each loop ? Commented Jan 22, 2017 at 14:28
  • Give $.data() a chance. Commented Jan 22, 2017 at 14:28
  • I'm sorry for that... I found that code by searching on SO and googling. I'm self-taught in jQuery.. Commented Jan 22, 2017 at 14:31
  • your variable is not global Commented Jan 22, 2017 at 14:33

2 Answers 2

2

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

5 Comments

@bona : glad to help :)
can you please help me as my condition udpated in the question? I want to add url in the attribute, then use it as link target and link text.
@bona : $(".data-cat").next().attr('href' , 'your value here')
I mean to get the link from data-url attribute, then append it to a tag as link target and link text. btw thanks before
@bona $(".data-cat").next().attr('href' , $ele.data('url'))
0

No need for each loop

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

Comments

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.