Catch name of tag span

Asked

Viewed 114 times

0

I need to take the generated name inside the id="pegname" and put inside the id="name", I did the code below, but it didn’t work.

The tag of the span id="pegname" generates the name of the client, in the case of Fulano da Silva and then with the script would return only the first name.

<span data-customer="name" id="pegarnome" ></span>
<span id="nome"></span>

<script>

    var str = document.getElementById("pegarnome").innerHTML;
    var res = str.split(" ",1);
    document.getElementById("nome").innerHTML = res;

</script>

1 answer

1

<script>    
    var str = document.getElementById("pegarnome").innerHTML;
    var arr = str.split(" ");
    var res = arr[0];
    document.getElementById("nome").innerHTML = res;
</script>

Split returns a String array, you can use it by passing to the element the first index of the array, which would be the first name.

  • It worked in parts, generating name within span only appears after the script for what I noticed, ie it does not take any attribute. I tested by manually putting a name inside the span and it worked.

Browser other questions tagged

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