Reputation: 23
I am trying to create a variable for each element in a set. I have an HTML structure like this:
<div id="notes">
<p>Example Text 1</p>
<p>Example Text 2</p>
<p>Example Text 3</p>
</div>
I want to store the text of each of the elements in a separate variable. In this case the elements are dynamically generated, so sometimes there are 2 elements, sometimes there are more.
What I have tried so far:
var $counter= 0;
var variableNote = {};
$('#notes p').each(function(){
$counter += 1;
variableNote["newNote"+$counter] = $("#notes p").text();
console.log(newNote1);
});
What I am doing wrong?
Upvotes: 1
Views: 451
Reputation: 4837
var variableNote = {};
$('#notes p').each(
(i,e) => variableNote["newNote" +(i+1)] = $(e).text()
);
console.log( variableNote );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notes">
<p>Example Text 1</p>
<p>Example Text 2</p>
<p>Example Text 3</p>
</div>
Upvotes: 2
Reputation: 4905
It can be done using vanilla javascript
var variableNotes = [...document.querySelectorAll("#notes p")].reduce((noteList, note, i)=>{
noteList['newNote'+ (i +1)] = note.innerText;
return noteList;
}, {});
console.log(variableNotes);
<div id="notes">
<p>Example Text 1</p>
<p>Example Text 2</p>
<p>Example Text 3</p>
</div>
Upvotes: 1
Reputation: 24965
This can be achieved by finding the elements and reducing them into a single object.
//lookup the p tags, and reduce them to a single object
var variableNotes = $('#notes p').get().reduce(function(notes, note, index){
notes['newNote'+ ++index] = note.innerText;
return notes;
}, {});
console.log(variableNotes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notes">
<p>Example Text 1</p>
<p>Example Text 2</p>
<p>Example Text 3</p>
</div>
Upvotes: 2
Reputation: 780818
Object properties are not variables. To access them you need to refer to the object.
Also, you're not using the current element of the iteration in your loop.
var variableNote = {};
$('#notes p').each(function(index) {
variableNote["newNote" + (index+1)] = $(this).text();
});
console.log(variableNote["newNote1"]);
Upvotes: 3