0

I have an array filled with HTML objects - in my case all of them are li items. I have to create new array with textContent from these lis. So I have two arrays:

A = [li, li, li, li, li];
B = [];

I've wrote such function:

function addContent() {
  for (let i = 0; i < A.length; i++) {
    let newConent = A[i].textContent;
    B.push(newConent);
  }
}

So my question is: is there any known method or more optimal way to do that? I'm interested in JavaScript approach.

Thanks in advance (x

1
  • 1
    is there any known method or more optimal way to do that do what exactly? Could you provide an example with input and expected output? Commented Mar 10, 2019 at 16:02

3 Answers 3

1

If A is an array, you can do it like this:

B = A.map(li => li.textContent)

But I don't think you really have an array. If you get elements by method like querySelectorAll, you need to make an array for it.

const lis = document.querySelectorAll('li')
const A = []

for (let i = 0; i < lis.length; i++) {
  A.push(lis[i])
}

const B = A.map(li => li.textContent)

console.log(B)
<li>a</li>
<li>b</li>
<li>c</li>

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

2 Comments

I'm sure that I have an array, I've checked in console that "proto" indicates that it's an array and "A instanceof Array" indicates the same
Then you can use map method.
1

You can use Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

let lis = Array.from(document.querySelectorAll('li'));
let texts = lis.map(li => li.textContent);
console.log(texts);
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>

Comments

1

You can use .map() to iterate over array of list items and return desired property values:

const list = [...document.querySelectorAll("li")];

const text = list.map(li => li.textContent);

console.log(text);
<ul class="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

Alternatively, you can also use a for...of loop:

const list = document.querySelectorAll("li");
const text = [];

for (item of list)
    text.push(item.textContent);

console.log(text);
<ul class="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

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.