最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get Value from html string? - Stack Overflow

programmeradmin1浏览0评论

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.

Share Improve this question edited Nov 26, 2019 at 3:22 Hoang Subin asked Nov 26, 2019 at 3:18 Hoang SubinHoang Subin 7,4608 gold badges42 silver badges58 bronze badges 4
  • 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
Add a ment  | 

1 Answer 1

Reset to default 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);

发布评论

评论列表(0)

  1. 暂无评论