<Response>
<SMSMessageData>
<Message>Sent to 1/1 Total Cost: NGN 2.2000</Message>
<Recipients>
<Recipient>
<number> 9109929199111</number>
<cost>NGN 2.2000</cost>
<status>Success</status>
<statusCode>101</statusCode>
<messageId>ATXid_f615eb5c6e901459e52d67d045a55355</messageId>
<messageParts>1</messageParts>
</Recipient>
</Recipients>
</SMSMessageData>
I want to just extract the element in the number tag using javascript (nodejs) code...............................................................................................
CodePudding user response:
you need to use a parser such as cheerio
then you need to read/provide data to it (the HTML), and then you can select the data you need by using its API:
const cheerio = require('cheerio');
const data = `
<Response>
<SMSMessageData>
<Message>Sent to 1/1 Total Cost: NGN 2.2000</Message>
<Recipients>
<Recipient>
<number> 9109929199111</number>
<cost>NGN 2.2000</cost>
<status>Success</status>
<statusCode>101</statusCode>
<messageId>ATXid_f615eb5c6e901459e52d67d045a55355</messageId>
<messageParts>1</messageParts>
</Recipient>
</Recipients>
</SMSMessageData>
</Response>
`;
const $ = cheerio.load(data);
const num = $('number').text();
console.log(num);
CodePudding user response:
Using the getElementsByTagName
which will return the element with the specified tag (in your case the number
tag). then you can select the first element use the innerText
property to extract the text value of the element.
const el = document.getElementsByTagName('number')[0];
console.log(el.innerText);
<Response>
<SMSMessageData>
<Message>Sent to 1/1 Total Cost: NGN 2.2000</Message>
<Recipients>
<Recipient>
<number> 9109929199111</number>
<cost>NGN 2.2000</cost>
<status>Success</status>
<statusCode>101</statusCode>
<messageId>ATXid_f615eb5c6e901459e52d67d045a55355</messageId>
<messageParts>1</messageParts>
</Recipient>
</Recipients>
</SMSMessageData>
CodePudding user response:
To do this, simply tell the system to fetch the HTML element by calling document.querySelector("number")
, and then use the innerText
property to get the text content of the string. Use the code below to set a variable content
to the text inside of the number tag.
var numberElement=document.querySelector("number"); //Fetch the element
var content=numberElement.innerText; //Retrieve its contents
CodePudding user response:
You can select a field by it's TagName, however its not a good solution (because you might have some other number fields in future). the better solution is using ID's. like:
const number=document.getElementById('ID').innerText;
or:
const number=document.querySelector('#ID').innerText;