我知道,这似乎是一个非常简单明了的问题,但请耐心等待一分钟。
可以说我们有一个看起来像这样的HTML文档:
<html>
<head>
<title>My Awesome Example.</title>
</head>
<body>
<p>World History is fascinating but can also be overwhelming because of its
sheer magnitude. Every historian brings their own <span class="blank-it">lens</span>
to historical interpretation so one must not only know the historical events but
also use <span class="blank-it">reasoning</span> skills to determine when a
historian's perspective is distorting the actual historical record.</p>
</body>
</html>
现在可以说我们要替换每次出现的<span class="blank-it">
,并用另一个元素和原始元素的innerHTML替换它。因此最终结果将类似于:
<input type="text" id="lens115">
<input type="text" id="reasoning118">
问题是该元素与文本内联。我想出了一些看起来像这样的代码:
// Get the element to be replaced
let blankhtml = document.getElementByClassnames("blank-it");
// Get the text we'll use as the ID of our new element
let blanktext = document.getElementByClassnames("blank-it").innerHTML;
// Create a variable to hold input text box code
let inputtext = '<input type="text" id="' . blanktext . '" class="blank-input">';
// Prepend the input box before the blankhtml element
// Remove the old element.
这就是我被困住的地方。因为似乎无论我使用insertBefore
还是removeChild
,它都希望我指定父元素。但是我怎么知道呢?在上面的示例中,它是一个简单的<p>
元素,但是如果代码看起来像这样:
<html>
<head>
<title>Something Goes Here</title>
</head>
<body>
<p>This is a <span class="important-text"><span class="blank-it">an important fact.</span><span>
</body>
</html>
理想情况下,在这种情况下,应该只有一个跨度,但是我们谈论的是用户输入的内容,所以我不能保证不会出现这种情况。
我确定这仍然是一个相当简单的问题,比告诉我使用replaceChild等要复杂得多。有什么想法吗?