如何使用JavaScript将内联html元素替换为另一个html元素之前和之后的文本?

问题描述 投票:1回答:1

我知道,这似乎是一个非常简单,直接的问题,但请耐心等待一分钟。

假设我们有一个看起来像这样的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等要复杂得多。有什么想法吗?

javascript html dom removechild
1个回答
0
投票

这对您来说是一个粗略的入门,它用一个以span的innerHTML作为值的输入替换了每个span。

首先,您需要遍历集合,创建一个新元素以替换现有元素,然后使用parentNode.replaceChild(newChild, existingChild)

let blanks = document.querySelectorAll(".blank-it");

blanks.forEach(function(el){
    const input = document.createElement('input')
    input.type='text';
    input.value = el.innerHTML;
    el.parentNode.replaceChild(input, el);
});
<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>
© www.soinside.com 2019 - 2024. All rights reserved.