0
<ul>
   <li>listitem1</li>
   <li>listitem2</li>
   <li>listitem13</li>
</ul>

I have something like this on HTML file. So how can I get that each list item in my jQuery file as array

like this

var asmg = ["listitem1","listitem2","listitem3"];
1
  • what have you tried so far? Commented Jun 9, 2018 at 15:08

6 Answers 6

1

use the jQuery.map() and .get() to process a plain array.

var asmg = $( "li" )
  .map(function() {
    return $(this).text();
 }).get();
 
 console.log(asmg);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>listitem1</li>
  <li>listitem2</li>
  <li>listitem13</li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

1

try with foreach loop :

function getArray(ul){
  asmg = [];
  ul.find('li').each(function(){
    asmg.push($(this).text());
  });
  return asmg;
}

console.log(getArray($('ul')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>listitem1</li>
  <li>listitem2</li>
  <li>listitem13</li>
</ul>

Comments

0

Try following

$(function(){
  var asmg = [];
  $("ul > li").each(function(i, li){
    asmg.push($(li).text());
  });
  console.log(asmg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>listitem1</li>
  <li>listitem2</li>
  <li>listitem13</li>
</ul>

Comments

0

You can use vanilla JavaScript to achieve this:

  1. Select all the li elements

    document.querySelectorAll('li')
    
  2. unpack them in an array

    [...document.querySelectorAll('li')]
    
  3. map this array to get the text content of each li item.

    [...document.querySelectorAll('li')].map(e => e.textContent)
    

Here is the code:

const li = [...document.querySelectorAll('li')].map(e => e.textContent)

console.log(li)
<ul>
  <li>listitem1</li>
  <li>listitem2</li>
  <li>listitem13</li>
</ul>

Comments

0
var asmg = Array.from(document.querySelectorAll('li')).map(e => e.textContent);

var asmg = Array.from(document.querySelectorAll('li')).map(e => e.textContent);
console.log(asmg);
<ul>
  <li>listitem1</li>
  <li>listitem2</li>
  <li>listitem3</li>
</ul>

Comments

0
var varObject = $('ul li').map(function(){
    return $(this).text();
}).get();

   //converting to array 
   var aiMsg = $.makeArray(varObject);

this code works for me.

thanks for all the answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.