Reputation: 499
I would like to create a basic generic function with jquery to put all elements of an html list into an Array. Everything seem to be ok but I meet some problems to get the return value. I know this is a basic problem so I hope you could help me to solve it.
<script>
function listeToArrayById(idListe){
$(function(){
var listChildren = $("#" + idListe).children(); //puts all li children in var listChildren
var arrayListChildren = [];
$.each(listChildren, function(key, value){
arrayListChildren.push($(this).text());
})
return arrayListChildren; // here it's ok arrayListChildren = ["a", "b", "c"]
})
}
var ulChildren = listeToArrayById("list1");
window.console.log(ulChildren); // here is my problem because ulChildren is undefined ... I should get an array ["a", "b", "c"]
</script>
</head>
<body>
<ul id="list1">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
</body>
Upvotes: 3
Views: 307
Reputation: 67187
You are using document ready handler
in a wrong way,
function listeToArrayById(idListe){
var listChildren = $("#" + idListe).children();
var arrayListChildren = [];
$.each(listChildren, function(key, value){
arrayListChildren.push($(this).text());
})
return arrayListChildren; // here it's ok arrayListChildren = ["a", "b", "c"]
}
$(function(){
var ulChildren = listeToArrayById("list1");
console.log(ulChildren);
});
And you could simplify your code like below,
function listeToArrayById(idListe){
return $("#" + idListe).children().map(function(){
return this.textContent
}).get();
}
Upvotes: 4