I'm trying to push multiple values into an array based on the elements ID.
I expect the outcome to be 3 and 4 but instead I get 1 2 3 4. Why is that the case in the following example?
var myArray = [];
$( '#bla' ).each( function() {
myArray.push( {
test: $( this ).text(),
});
});
console.log( myArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>1</div>
<div>2</div>
<div id="bla">3</div>
<div id="bla">4</div>
</div>
3 Answers 3
You are seeing the content of the your HTML, and not the console.log.
This is what you need to fix:
- Include jQuery
- Use class instead of id - there can be only one id in a document, so you'll get only one result
- Look at the console
var myArray = [];
$( '.bla' ).each( function() {
myArray.push( {
test: $( this ).text(),
});
});
console.log( myArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>1</div>
<div>2</div>
<div class="bla">3</div>
<div class="bla">4</div>
</div>
Comments
First id has to be unique replace id with class and use your snippet
var myArray = [];
$( '.bla' ).each( function() {
myArray.push( {
test: $( this ).text(),
});
});
console.log( myArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>1</div>
<div>2</div>
<div class="bla">3</div>
<div class="bla">4</div>
</div>
Comments
First of all, you can't have two HTML elements with same id attribute. It is unique indeficator, it should be only one on page.
And second, if you are using your js script from external (not inluded between <scritp></script>) you should use (document.ready or in jQuery $(docuemnt).ready(function(){}) [in my case it is short way to do this]), because you don't want to read HTML values before your is not loaded.
(function () {
var myArray = [];
$( '.bla' ).each( function() {
myArray.push( {
test: $( this ).text(),
});
});
console.log( myArray );
}());
<div>
<div>1</div>
<div>2</div>
<div class="bla">3</div>
<div class="bla">4</div>
</div>
1 Comment
id with class
jQuerywhich you haven't tagged in your question so be sure to check you have included thejQuerylibrary and you shouldn't duplicate ID's. ID's are supposed to be unique. I would recommend you swap from usingid's to using aclassname. While testing things injavascript/jQueryI would also recommend you open the browser console so you can see any errors that might be reported/given. This will also tell you the cause of error and which line this error has occurred on.1 2 3 4from that code