Extract element by ID from string?

后端 未结 2 1433
失恋的感觉
失恋的感觉 2021-02-20 05:59

I have a string which contains this text:




    ExtractDiv test



        
2条回答
  •  不要未来只要你来
    2021-02-20 06:34

    You can create a temporary element, put the HTMLString as a content to it, then use querySelector to get an element with passed id. Something like this:

    function ExtractElementByIdFromString(HTMLString, IdString) {
        var result,
            temp = document.createElement('div'); // Create a temporary element
        temp.innerHTML = HTMLString; // Set the passed string as HTML to the temporary element
        result = temp.querySelector('#' + IdString).outerHTML; // Find an element with the passed id
        return result;
    }
    

    A working demo at jsFiddle.

提交回复
热议问题