spencer.sm
spencer.sm

Reputation: 20634

Concatenate object text values with for loop - Javascript

I'm trying to take an array of names and add them to a single variable using a for loop then display it to the console.

var list = "";
var names = document.getElementsByTagName('h3');

for(i=0;i<names.length;i++){
    list = list.concat(names[i].firstChild);
}

console.log(list);

But it outputs a long list of:

[object Text][object Text][object Text][object Text][object Text][object Text][object Text]


Note:
console.log(names[22].firstChild) outputs "Richard" in the console just fine. I'm just having problems concatenating them to the variable list.


The code of the is as follows.

<h3 style="color:white; font-weight:300;" class="staff">
  Richard Smith<br>
  <span style="font-size:14px;">Data Analyst</span>
</h3>

That is why I used .firstChild. If I use .innerText it returns both the name and the <span> that follows it.

Upvotes: 1

Views: 3441

Answers (2)

SillasSoares
SillasSoares

Reputation: 382

Use nodeValue

var list = "";
var names = document.getElementsByTagName('h3');

for(i=0;i<names.length;i++){
    list = list.concat(names[i].firstChild.nodeValue + ' ');
}

console.log(list);

JsFiddle

Upvotes: 1

Andrew Mairose
Andrew Mairose

Reputation: 11015

The names[i].firstChild attribute references a text node that contains the value you would like to get at.

Instead of accessing the firstChild attribute, use innerHTML or innerText to get a string rather than a text node.

I added a space in between each name as well.

var list = "";
var names = document.getElementsByTagName('h3');

for (i = 0; i < names.length; i++) {
  list = list.concat(names[i].innerHTML.split('<br>')[0] + ' ');
}

console.log(list);
<h3 style="color:white; font-weight:300;" class="staff">
  Richard Smith<br>
  <span style="font-size:14px;">Data Analyst</span>
</h3>

EDIT:

Updated answer after OP posted HTML.

With the HTML structure you are using, the innerText attribute will retrieve the job title as well.

If all of your <h3> tags are formatted the same way, you can get the innerHTML, then split the string at the <br>, then take the first half that contains the name and append it to your list.

Upvotes: 2

Related Questions