Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get span elements within div using javascript

I have a html code:

<div id="id0" class="class0">
    <span> "1" </span>
    <span> "2" </span>
    <span> "3" </span>
</div>

The question is how can I get 1,2,3 as a list using javascript?

I tried: document.getElementById and document.getElementsByClassName But none works.

like image 873
Nessi Avatar asked Dec 23 '22 18:12

Nessi


2 Answers

You can use map and then remove the quoted marks to get only the number list

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Test</title>
</head>
<body>
  <div id="id0" class="class0">
    <span> "1" </span>
    <span> "2" </span>
    <span> "3" </span>
  </div>
  
  <script>
    console.clear();
    const selectors = document.querySelectorAll('#id0 > span');
    const list = [...selectors].map(span => parseInt(span.innerText.replace(/"/g,"")));
    console.log(list)
  </script>

</body>
</html>
like image 184
Sifat Haque Avatar answered Dec 31 '22 11:12

Sifat Haque


You can use map() on children on container div

const cont = document.getElementById('id0');
const res = [...cont.children].map(x => x.innerHTML);
console.log(res)
<div id="id0" class="class0">
    <span> "1" </span>
    <span> "2" </span>
    <span> "3" </span>
</div>
like image 20
Maheer Ali Avatar answered Dec 31 '22 10:12

Maheer Ali