简体   繁体   English

选择HTML文本的特定部分

[英]Selecting specific part of an HTML text

I have a function that returns some HTML fragment that I store in a variable called data , with its whole structure. 我有一个函数返回一些HTML片段,我将其存储在一个名为data的变量中 ,其整体结构。 What I want is to extract from it some of those parts. 我想要的是从中提取一些这些部分。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script id="hello">

    </script>
</head>
<body>

</body>
</html>

For example, I want to get the body and save it in a new variable: 例如,我想获取正文并将其保存在一个新变量中:

var body = data.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];

Where data is the HTML text as a string that the original function is returning. 数据是HTML文本作为原始函数返回的字符串

Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable?? 有没有什么办法可以保存特定的脚本,从它的ID(在这种情况下使用id = hello),并将其保存在另一个变量?

Thank you very much 非常感谢你

var newVar = $("#hello").html();

Let's suppose you have an HTML string in a variable, for example 例如,假设您在变量中有一个HTML字符串

var foo = '<body><span>bar</span></body>';

Now, let's initialize a parser, to convert this into HTML: 现在,让我们初始化一个解析器,将其转换为HTML:

var parser = new DOMParser();
var doc = parser.parseFromString(foo, "text/html");

Now, you can read anything from foo , as it is converted into HTML: 现在,您可以从foo读取任何内容,因为它被转换为HTML:

document.getElementsByTagName("body")[0].innerHTML = doc.querySelectorAll("body")[0].innerHTML;

 $html = document.querySelector("body").innerHTML; $hello = document.getElementById("hello").innerHTML; console.log($html); console.log($hello); 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script id="hello"> // script data </script> </head> <body> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM