Parsing specific HTML tags in Javascript

丶灬走出姿态 提交于 2020-01-24 17:12:06

问题


I'm looking for the Javascript to parse the following HTML:

<p>random text random text random text random text</p>
<kbd><h2>Heading One</h2>Body text Body text Body text Body text</kbd>
<p>random text random text random text random text</p>

... and return just:

Heading One

In other words, I'd like to strip all tags and Body Text from within the <kbd> tags.

Any ideas would be greatly appreciated!


回答1:


var input = /* that HTML string here */;
var div = document.createElement('div');

div.innerHTML = input;

var h2 = div.getElementsByTagName('h2')[0];
var text = h2.innerText || h2.textContent;

alert(text); // alerts "Heading One"

Reference:

  • document.createElement
  • innerHTML
  • element.getElementsByTagName
  • Node.textContent (Quirksmode compatibility table)

Demo:

  • http://jsfiddle.net/mattball/vaVPF/



回答2:


Regex?

var s = "<p>random text</p>\n" +
  "<kbd><h2>Heading One</h2>Body text</kbd>\n" +
  "<p>random text</p>";

s.match(/<h2>(.*?)<\/h2>/)[1] // == "Heading One"

This matches group one as the shortest possible (.*?) string between <h2>...</h2>.

You can find all matches using the g option.

s.match(/<h2>(.*?)<\/h2>/g) // == ["<h2>Heading One</h2>"]

Note that groups are not accessible.

For multiline content between tags, use

s.match(/<tag>[\s\S]*?<\/tag>/ig)



回答3:


if you include jquery (jquery.com) you can do this:

var heading=$("h2").html();


来源:https://stackoverflow.com/questions/7869393/parsing-specific-html-tags-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!