Home > Back-end >  How to get only text in array?
How to get only text in array?

Time:01-21

There is a list now i'm trying to get list data in array using push but there is getting only classes instead of text. How to fix this?

My Code:-

$(function() {
  $('button').click(function() {
    let tags = [];
    tags = $('span.tag').each(function() {
      tags.push($(this).text());
    });
    console.log(tags);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span >test</span>
<span >new</span>


<button>Get Value</button>

ThankYou!

CodePudding user response:

You have selected the targets using $('span.tag'). You have to loop it corrctly.

You can either loop through each elements in the selector and access the text with $(node).text() where node is the each element in the selector.

You can run a each and push that to tags array with

$('span.tag').each(function (index, node) {
    tags.push($(node).text());
});

Working Fiddle

$(function () {
    $('button').click(function () {
        let tags = [];
        $('span.tag').each(function (index, node) {
            tags.push($(node).text());
        });
        console.log(tags);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span >test</span>
<span >new</span>


<button>Get Value</button>

Array.map implementation

$(function () {
    $('button').click(function () {
        const tags = Array.from($('span.tag').map((index, node) => $(node).text()));
        console.log(tags);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span >test</span>
<span >new</span>

<button>Get Value</button>

  •  Tags:  
  • Related