How to get all the value from an array object using javascript?

How to get all value for an array object using javscript?

Html example:

<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 reach it

+4
source share
5 answers

I think you are 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

According to the comment you can also use .map()

var array_of_name= $(".my_name").map(function(){
        return $(this).text();
 }).get();

 console.log(names);

Docs

Demo

Demo with .map ()

+6
source

You can try the following:

$(function(){
    var names = $(".my_name").map(function(){
        return $(this).text();
    }).get();
    console.log(names);
})
+4
source

(MSIE >= 9) JavaScript:

var names = [].map.call(document.getElementsByClassName('my_name'), function(el) {
    return el.textContent;
});

: Array.prototype.map

+2

Javascript :

 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);
+1

:

$(function(){
    var data = [];
    $(".my_name").text(function(key,value){
       data.push(value);
    });
 console.log(data);
})
0

Source: https://habr.com/ru/post/1545805/


All Articles