On search/highlight click -> existing div becomes wrapped with existing span

随声附和 提交于 2019-12-12 02:19:02

问题


I have a problem with javascript search and highlight text. For example, there is existing span element and existing div element. Problem is that if I click on search button for some reason div element becomes a child of span element.

To explain it better I have created JS fiddle to show the problem:

function highlightSearch() {

    $('span').removeClass('highlighted');
    var text = document.getElementById('query').value;
    var query = new RegExp("(\\b" + text + "\\b(?!([^<]+)?>))", "gim");
    var e = document.getElementById("searchText").innerHTML;
    var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
    document.getElementById("searchText").innerHTML = enew;
    var newe = enew.replace(query, "<span class='highlighted'>$1</span>");
    document.getElementById("searchText").innerHTML = newe;
}

Check problem on : JSfiddle


回答1:


Well, you are removing all </span> tags from the innerHTML in this line:

var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");

And therefore also the </span> of .glyphicon. This is why the element becomes wrapped.

Btw: An exception is thrown: ReferenceError: highlightSearch is not defined



来源:https://stackoverflow.com/questions/37568862/on-search-highlight-click-existing-div-becomes-wrapped-with-existing-span

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!