0

I'm new to jQuery selectors. How can I extract the values from an attribute?

Given:

<div class='container'>
<div class='entry' data-name='foo'></div>
<div class='entry' data-name='bar'></div>
<div class='entry' data-name='baz'></div>
</div>

I'd want to extract: ['foo','bar','baz']

1
  • I had expected to be able to iterate through something like jQuery('.entry')[0].attr('data-name') but that doesn't seem to work. Nor does jQuery('.entry')[0].attributes.data-name Commented Nov 24, 2014 at 4:40

3 Answers 3

2

You can use .map() to create an array from a set of dom elements like

var array = $('.container .entry').map(function () {
    return $(this).data('name')
}).get();
Sign up to request clarification or add additional context in comments.

1 Comment

@diEcho that depends on whether OP wants an array or a string... from ['foo','bar','baz'] it looks like OP wants an array
1

try this

$(function () {
    var array = [];
    $(".entry").each(function () {
        array.push($(this).data("name"));
    });
    console.log(array);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='entry' data-name='foo'></div>
<div class='entry' data-name='bar'></div>
<div class='entry' data-name='baz'></div>
</div>

Comments

1

Try

var name = [];
$('div.container').children().map(function() {  
    name.push($(this).data('name'));
});

Working DEMO

2 Comments

If you're using map no need to create an array variable
name is an array varaible

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.