Extract element by ID from string?

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

I have a string which contains this text:




    ExtractDiv test



        
相关标签:
2条回答
  • 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.

    0 讨论(0)
  • 2021-02-20 06:35

    You can parse an HTML string with the native DOMParser:

    var str = "<!DOCTYPE……………" // your HTML string
    
    var doc = new DOMParser().parseFromString(str, "text/html")
    

    Then just use regular DOM methods:

    console.log( doc.getElementById("main") )
    

    Note that using a DOMParser is more efficient and safer than inserting the string somewhere in your document's innerHTML, because only the structure will be created — <script> elements won't be executed, images won't be loaded, CSS will no try to apply to it, no rendering will occur, etc.

    0 讨论(0)
提交回复
热议问题