1

A bit difficult to explain....I'm trying to get the attribute of this repeating div. Code below..

<div class="hidden-data">
    <div class="menu-data" data-title="About"></div>
    <div class="menu-data" data-title="Team"></div>
    ETC/ETC/ETC
</div>

Right now I'm calling...

  var data = $(".menu-data").attr("data-title");

and only getting the first one, 'About'. I'd like to find a way to pass each 'data-title' attribute into an array.

Thoughts? I'm kind of stumped here, also having trouble Googling for this one..

Thanks!

2
  • How do you want those attributes to be returned as comma separated? Commented Sep 27, 2017 at 18:37
  • Was hoping i could get them into an array. Commented Sep 27, 2017 at 18:37

3 Answers 3

3

Jquery

var array = [];
$(".menu-data").each(function() {
   array.push($(this).attr("data-title"));
});

Js Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

You the man, Rex!! Thanks. Gotta work out my push muscles more!
0

that's because when you call the data method on the jQuery object, it returns the data for the first element in the nodeList. To get the data for all the div's you have to loop through the elements with the $.each method or use a mapping to retrieve the attributes in a list.

Comments

0

you can use eq to get an equal that you want or use each to get each one

	var data = $(".menu-data").eq(0).data('title');
  console.log('eq(0) : ' + data);
  
  var data = $(".menu-data").eq(1).data('title');
	console.log('eq(1): ' + data);
  
  $(".menu-data").each(function(){
  console.log('each: ' + $(this).data('title'));
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hidden-data">
    <div class="menu-data" data-title="About"></div>
    <div class="menu-data" data-title="Team"></div>
    ETC/ETC/ETC
</div>

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.