How to extract only phone numbers from div with javascript?

Viewed 48

I have a div that contains texts and phone numbers

<div>
    <span>+1 704 849 3340</span>
    <span>+5 662-325-5582</span>
    <span>+8 804-896-4087</span>
    <span>+545 804-896-4087</span>
    <span>5854</span>
    <span>text</span>
</div>

How can I access the phone numbers in javascript, that start with a +?

1 Answers

is this what you desire the code to do?

const tags = document.getElementsByTagName("span");
const filteredTags = [];


for(let i = 0; i < tags.length; i++){

  if(tags[i].innerHTML[0] == '+')
    filteredTags.push(tags[i].innerHTML);
}

console.log(filteredTags);
<body>
<span>+1 704 849 3340</span>
<span>+5 662-325-5582</span>
<span>+8 804-896-4087</span>
<span>+545 804-896-4087</span>
<span>5854</span>
<span>text</span>
</body>

Related