How to get all value to array object using javascript ?
example html :
<tr>
<td class="my_name">udin</td>
<td class="my_name">juned</td>
<td class="my_name">saepudin</td>
</tr>
how to get all value from class = "my_name" using javascript ?
my javascript :
<script>
$(document).ready(function() {
var array_of_name = $(".my_name");
// how to get all value from my object array ?
// i want get result like this : ["udin", "juned", "saepudin"] ?
});
</script>
how to achieve it?
How to get all value to array object using javascript ?
example html :
<tr>
<td class="my_name">udin</td>
<td class="my_name">juned</td>
<td class="my_name">saepudin</td>
</tr>
how to get all value from class = "my_name" using javascript ?
my javascript :
<script>
$(document).ready(function() {
var array_of_name = $(".my_name");
// how to get all value from my object array ?
// i want get result like this : ["udin", "juned", "saepudin"] ?
});
</script>
how to achieve it?
Share Improve this question edited Nov 18, 2019 at 11:41 Mosè Raguzzini 15.9k1 gold badge34 silver badges46 bronze badges asked Jun 24, 2014 at 8:47 tardjotardjo 1,6546 gold badges25 silver badges39 bronze badges 4-
You don't have any
array
in your example. – emerson.marini Commented Jun 24, 2014 at 8:48 - What you want is to get the values of a collection of elements selected: api.jquery./each and api.jquery./html – emerson.marini Commented Jun 24, 2014 at 8:48
- I think he meant 'to' not 'from' – Alex Char Commented Jun 24, 2014 at 8:49
- wrap text into DIV tag. var array_of_name = $(".my_name div"); You may want to play with Jquery JSON, and apply stringify to the object. – Dmitry Commented Jun 24, 2014 at 8:50
5 Answers
Reset to default 6I think you're looking for this:
$( document ).ready(function() {
var array_of_name = [];
$(".my_name").each(function(){
array_of_name.push($(this).text());
});
console.log(array_of_name); // will get result like this : ["udin", "juned", "saepudin"] ?
});
OR
As per the ment you can use .map()
too
var array_of_name= $(".my_name").map(function(){
return $(this).text();
}).get();
console.log(names);
Docs
.each()
.push()
Demo
Demo with .map()
You may try this:
$(function(){
var names = $(".my_name").map(function(){
return $(this).text();
}).get();
console.log(names);
})
With modern browsers (MSIE >= 9) you can do this quite easily in plain JavaScript:
var names = [].map.call(document.getElementsByClassName('my_name'), function(el) {
return el.textContent;
});
Demo
See also: Array.prototype.map
In Javascript
, you can achieve it like this:
var array_of_name = [];
var elements_arr = document.getElementsByClassName("my_name");
for (var i in elements_arr) {
array_of_name.push(elements_arr[i].innerHTML);
}
console.log(array_of_name);
try this :
$(function(){
var data = [];
$(".my_name").text(function(key,value){
data.push(value);
});
console.log(data);
})