0

I have some tabular data and I need to put them into an array so I can look for a match elsewhere in the code. So I need to convert this:

<td> Name 1 </td>
<td> Name 2 </td>
<td> Name 3 </td>

into:

['Name 1', 'Name 2', 'Name 3']

This does not work:

 $('td').text().toArray();

I really hoped it would :) I need to take the text of an input and compare it to the existing <td>s to make sure it's unique, so if there is a better way of going about it, I'd love to hear it. I know I could create an empty array, create a loop or use $.each() and push() each .text() to the array, but there has got to be a more concise way.

1

2 Answers 2

2

You can use jQuery map() method like following.

var arr = $('td').map(function (){
    return $(this).text().trim();
}).get();

console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td> Name 1 </td>
        <td> Name 2 </td>
        <td> Name 3 </td>
    </tr>
</table>

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

3 Comments

Yeah I never quite grasped the .map() and .get(). Thanks!
@Azim maybe you can tell me - when do you know when .get() will be necessary? I know the documentation says .get() "Retrieves the DOM elements matched by the jQuery object". So when you have a matched set returned from a normal jQuery selector, how do you know you also need to then do a .get() to "retrieve" the items already in the matched set?
map() returns a jQuery object. get() returns an array containing each element in a jQuery object (plain JS array). @SpaceNinja
1

You need to loop over the elements and get each one's text. In plain js you could do :

var result = Array.prototype.map.call(document.getElementsByTagName("td"), function(el) {
        return el.innerHTML.trim();
    });

    console.log(result)
<table>
    <tr>
        <td> Name 1 </td>
        <td> Name 2 </td>
        <td> Name 3 </td>
    </tr>
</table>

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.