Picking an attribute from a class in javascript

Asked

Viewed 319 times

3

Hi, I’m developing a list with all my facebook friends.

I managed to create the first line of the code, which makes me take all my friends and store them in a variable within an array, as shown below:

var info = document.getElementsByClassName("_52jh _5pxc");

Then when I ask to see the elements the following message is shown:

info[0];
<h3 class="_52jh _5pxc"><a href="/urldouser?ref=bookmarks">Nome Do Usuário</a></h3>

What I need to do, is take the "Username" and I’m not getting it, I tried to use the

var names = info[0].getAtributte("a");

But it returns to me null, how could I solve this, to the point of being able to catch what is after the opening. >"Nome Do Usuário"<.

I believe it is a simple answer, however, I am starting the web phase now and I have some difficulties, I thank you already.

1 answer

3


The element a is not an attribute of h3 but a direct descendant, so we can not use getAtributte.

But you can use it like this, which uses the element itself as a starting point:

var names = info[0].querySelector("a").innerHTML;

In fact you can catch everyone doing so:

var nomes = [].map.call(document.querySelectorAll('._52jh._5pxc a'), function(el) {
    return el.innerHTML;
});

jsFiddle: https://jsfiddle.net/zx7pyjm3/

  • 1

    Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.