简体   繁体   English

使用javascript将标签添加到HTML

[英]Adding tags to HTML using javascript

I have HTML produced from XSLT that looks like: 我有从XSLT生成的HTML,看起来像:

<span id="text">It's like what Sir Ian McKellan told me the day I sold my boat to Karl Lagerfeld: <span id="quote">Parting is such sweet sorrow.</span></span>

I'm trying to use javascript to parse it such that extra tags are added to mark the context around the quote. 我正在尝试使用javascript进行解析,以便添加额外的标记来标记引号周围的上下文。 The goal is to give users the option whether or not to display the quote plus context or just the quotation. 目的是使用户可以选择是否显示引号加上上下文或仅显示引号。 The end result would be, eg, 最终结果将是例如

<span id="text"><span id="preContext">It's like what Sir Ian McKellan told me the day I sold my boat to Karl Lagerfeld: </span><span id="quote">Parting is such sweet sorrow.</span></span>

This way, it would be simple to define the style.display of preContext as none. 这样,将preContext的style.display定义为none会很简单。 I've tried using insertAdjacentHTML; 我已经尝试过使用insertAdjacentHTML; for example, 例如,

document.getElementById("text").insertAdjacentHTML('afterbegin', "<span id='preContext'>");
document.getElementById("quote").insertAdjacentHTML('beforebegin', "</span>");

But, as I've discovered, insertAdjacentHTML can insert nodes but not individual tags. 但是,正如我发现的那样,insertAdjacentHTML可以插入节点,但不能插入单个标签。 The above gets me <span id="text"><span id="preContext"></span>It's like. . . 上面让我<span id="text"><span id="preContext"></span>It's like. . . <span id="text"><span id="preContext"></span>It's like. . .

Is this possible in javascript, or does this need to be done in XSLT? 这在javascript中是否可行,还是需要在XSLT中完成? (PS: I don't want to use JQuery. . ) (PS:我不想使用JQuery。)

Working example: http://jsfiddle.net/vcSFR/1/ 工作示例: http : //jsfiddle.net/vcSFR/1/

This code gets the first textNode, wraps it in a span, and then swaps the original first text node for the new span. 此代码获取第一个textNode,将其包装在一个范围中,然后将原始的第一个文本节点交换为新的范围。

var oDiv = document.getElementById("text");
var firstText = "";
for (var i = 0; i < oDiv.childNodes.length; i++) {
    var curNode = oDiv.childNodes[i];
    if (curNode.nodeName === "#text") {
        firstText = curNode.nodeValue;
        break;
    }
}
firstTextWrapped = '<span id="preContext">' + firstText + '</span>';
oDiv.innerHTML = oDiv.innerHTML.replace(firstText, firstTextWrapped);

Thanks to https://stackoverflow.com/a/6520270/940252 for the code to get the first textNode. 感谢https://stackoverflow.com/a/6520270/940252提供了获取第一个textNode的代码。

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

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