Reputation: 15394
I'm not getting very far with the following, and am seeking an understanding of the process please.
I have this HTML
<span data-credit-name="Name_1"><strong>1</strong> Name 1</span><br />
<span data-credit-name="Name_2"><strong>2</strong> Name 2</span><br />
<span data-credit-name="Name_3"><strong>1</strong> Name 3</span><br />
<span data-credit-name="Name_4"><strong>1</strong> Name 4</span><br />
<span data-credit-name="Name_5"><strong>3</strong> Name 5</span><br />
<span data-credit-name="Name_6"><strong>1</strong >Name 6</span><br />
<span data-credit-name="Name_7"><strong>4</strong> Name 7</span><br />
What I would like to do is iterate through each span and collect its data-credit-name and the value within the strong tag and create a js object looking like so
var credit = {Name_1:"1", Name_2:"2", Name_3:"3"};
I've tried this to get the first one but get empty string returned:
var credit = $('span[data-credit-name]:first').text();
console.log(credit);
Upvotes: 0
Views: 70
Reputation: 2083
To get the data attributes you should use the jQuery .data()
method. You can iterate like so:
var credit = {};
$("span[data-credit-name]").each(function(){
var key = $(this).data("credit-name");
var value = $(this).find("strong").text();
credit[key] = value;
});
var credit = {};
$("span").each(function(){
var key = $(this).data("credit-name");
var value = $(this).find("strong").text();
credit[key] = value;
});
console.log(credit);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-credit-name="Name_1"><strong>1</strong> Name 1</span><br />
<span data-credit-name="Name_2"><strong>2</strong> Name 2</span><br />
<span data-credit-name="Name_3"><strong>1</strong> Name 3</span><br />
<span data-credit-name="Name_4"><strong>1</strong> Name 4</span><br />
<span data-credit-name="Name_5"><strong>3</strong> Name 5</span><br />
<span data-credit-name="Name_6"><strong>1</strong >Name 6</span><br />
<span data-credit-name="Name_7"><strong>4</strong> Name 7</span><br />
Upvotes: 3
Reputation: 26163
This should do the trick...
var credit = {};
$("span[data-credit-name]").each(function() {
credit[$(this).data("credit-name")] = $(this).find("strong").text();
});
jsfiddle example...
Upvotes: 4
Reputation: 63587
var out = {};
$.each($('span'), function (i, el) {
var $this = $(this);
var strong = $this.find('strong').html();
var data = $this.data('credit-name');
out[data] = strong;
});
Upvotes: 1
Reputation: 35223
You can map
the desired values and use get()
to unwrap the result from jQuery objects.
On top of my head:
var result = $('span[data-credit-name]').map(function(i, el){
var ret = {},
$span = $(el),
creditName = $span.data('credit-name');
ret[creditName] = ++i;
return ret;
}).get();
console.log(result);
http://jsfiddle.net/5d09bo4c/2/
(Based on your latest HTML change in the question)
Upvotes: 1