You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将jQuery的.html()方法替换为getElementById指定输出容器?

问题

如何将jQuery的.html()方法替换为原生的getElementById?

现有一段在div内搜索文本并高亮的JS代码,当前通过.html()将结果输出到.len_span元素中,希望改为将结果显示在id为plus的元素里,实现自由控制结果展示位置。

解决方案

直接将原代码中操作.len_span的jQuery代码替换为原生DOM操作即可,核心修改点如下:

  1. 当搜索框有输入时,将结果赋值给plus元素的innerHTML:
document.getElementById("plus").innerHTML = "Total " + $(this).find(".my-pp-highlight").length + " Result Found.";
  1. 当搜索框清空时,清空plus元素的内容:
document.getElementById("plus").innerHTML = "";

修改后的核心代码片段

if (searchTerm.length > 0) {
  $(".my-pp-ppl").each(function (index) {
    // 替换原jQuery的.html()为原生DOM操作
    document.getElementById("plus").innerHTML = 
      "Total " + $(this).find(".my-pp-highlight").length + " Result Found.";
  });
} else {
  // 清空目标元素内容
  document.getElementById("plus").innerHTML = "";
}

完整修改后的代码

<!-- Hosted Plugins -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js' type='text/javascript'></script>

<style>
/* Highlight */
.my-pp-highlight {background-color:yellow; color: black}

#my-pp-text-search{
border: 1px solid red; 
height: 50px; 
width: 110px; 
display: block;
font-size: 14px; 
background: #fdc; 
margin-bottom: -20px !important;}

#my-pp-text-search:focus {outline: none !important;}
</style>

<input id='my-pp-text-search' placeholder='Find Words....' type='text'/>
<br>
<span class='len_span'></span>

<div class='my-pp-ppl' id='post-body'>
What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

<h2 id="plus"></h2>

<script type='text/javascript'>
  // Main Highlight
  $(function () {
    $("#my-pp-text-search").bind("keyup change", function () {
      var searchTerm = $(this).val();

      $(".my-pp-ppl").removeHighlight();

      if (searchTerm) {
        $(".my-pp-ppl").highlight(searchTerm);
      }

      //my-pp-highlight
      if (searchTerm.length > 0) {
        $(".my-pp-ppl").each(function (index) {
          // 使用原生DOM操作替换jQuery的.html()
          document.getElementById("plus").innerHTML = 
            "Total " + $(this).find(".my-pp-highlight").length + " Result Found.";
        });
      } else {
        // 清空目标元素
        document.getElementById("plus").innerHTML = "";
      }
    });
  });
</script>

<script type='text/javascript'>
//<![CDATA[
 (jQuery.fn.highlight = function (a) {
    function b(a, e) {
      var g = 0;

      if (3 == a.nodeType) {
        var h = a.data.toUpperCase().indexOf(e);

        if (h >= 0) {
          var f = document.createElement("span");
          f.className = "my-pp-highlight";

          var c = a.splitText(h);
          c.splitText(e.length);

          var i = c.cloneNode(!0);
          f.appendChild(i), c.parentNode.replaceChild(f, c), (g = 1);
        }
      } else if (
        1 == a.nodeType &&
        a.childNodes &&
        !/(script|style)/i.test(a.tagName)
      )
        for (var d = 0; d < a.childNodes.length; ++d)
          d += b(a.childNodes[d], e);
      return g;
    }

    return this.each(function () {
      b(this, a.toUpperCase());
    });
  }),
    (jQuery.fn.removeHighlight = function () {
      function a(c) {
        for (var d = 0, f = c.childNodes, g = f.length; d < g; d++) {
          var b = f[d];

          if (1 == b.nodeType) {
            a(b);
            continue;
          }

          if (3 == b.nodeType) {
            var e = b.nextSibling;

            if (null != e && 3 == e.nodeType) {
              var h = b.nodeValue + e.nodeValue;

              (new_node = c.ownerDocument.createTextNode(h)),
                c.insertBefore(new_node, b),
                c.removeChild(b),
                c.removeChild(e),
                d--,
                g--;
            }
          }
        }
      }
      return this.find("span.my-pp-highlight")
        .each(function () {
          var b = this.parentNode;

          b.replaceChild(this.firstChild, this), a(b);
        })
        .end();
    });
 //]]>
</script>

内容的提问来源于stack exchange,提问作者Asma Binta Younus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:00:52