Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

shu Chan
shu Chan
2,951 Points

HTML/JS alerting a specific part of an array and not DOM objects

Hello! I'm trying to alert a specific part of an array I create when i get an element through a tag. Here is the HTML portion

<p id="intro">
  Hello World!
</p>

<p id="info">
  JavaScript on The DOM
</p>

Here is the javascript portion I'm working on

var elm = document.getElementsByTagName('p');
alert(elm);

I don't know how to create an array of only words and not DOM objects, I also don't know how to specify a specific part of the array to alert.

Any help would be appreciated

1 Answer

Steven Parker
Steven Parker
229,732 Points

To convert the element collection into an array of the text parts you could do something like this:

var elm = document.getElementsByTagName('p');
var words = Array.from(elm).map(p => p.textContent); // convert texts into array
alert(words);
shu Chan
shu Chan
2,951 Points

Ok but how would I alert a specific part of an array? Like alert(words[1])?

Ah, I figured it out, thank you.