1

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.

2
  • try to use not firstChild but innerText Commented Sep 11, 2015 at 19:08
  • @jfriend00 Because list is a string Commented Sep 11, 2015 at 19:10

2 Answers 2

2

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.

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

1 Comment

the trick is to use innerText. It seems + ' ' isn't necessary (also, it is not the same as the code in the question. Extra spaces.)
1

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

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.