I have a html string like this which response from API:
const response = `
<html>
<head>
<title></title>
</head>
<body>
<code>Value I want to get<br></code>
</body>
</html>
`;
So the content maybe dynamic but the tag <code>
is unique. I want to have some more solutions on this to see what is the best solution.
I have a html string like this which response from API:
const response = `
<html>
<head>
<title></title>
</head>
<body>
<code>Value I want to get<br></code>
</body>
</html>
`;
So the content maybe dynamic but the tag <code>
is unique. I want to have some more solutions on this to see what is the best solution.
-
document.getElementsByTagName("code")
is what you should be looking for – Prasanna Commented Nov 26, 2019 at 3:22 - 2 "I want to have some more solutions…" You haven't shown any solutions, so this is just a request for free code. – RobG Commented Nov 26, 2019 at 3:23
-
Nope. This string e from API and we cannot get the value inside
<code>
by document. – Hoang Subin Commented Nov 26, 2019 at 3:23 - 1 @HoangTranSon yeah didn't see the string thing. Someone has already provided a correct answer to your question. – Prasanna Commented Nov 26, 2019 at 3:25
1 Answer
Reset to default 9You could use a DOMParser
to convert your HTML string into a Document object which you can then use querySelector()
to get your desired value:
const response = `
<html>
<head>
<title></title>
</head>
<body>
<code>Value I want to get<br></code>
</body>
</html>
`;
const {body} = new DOMParser().parseFromString(response, 'text/html');
const value = body.querySelector('code').innerText; // find <code> tag and get text
console.log(value);