4

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.

4
  • document.getElementsByTagName("code") is what you should be looking for 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. Commented Nov 26, 2019 at 3:23
  • Nope. This string come from API and we cannot get the value inside <code> by document. 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. Commented Nov 26, 2019 at 3:25

1 Answer 1

9

You 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.