Extract item by id from string?

I have a line that contains this text:

<!DOCTYPE html>
<html>
<head>
    <title>ExtractDiv test</title>
</head>
<body>
    <p>Apples and oranges</p>
    <div id="main">
        <ul style="list-style-type: upper-roman">
            <li>&#196;pfel</li>
            <li>Birnen</li>
        </ul>
    </div>
    <p>Men and women</p>
</body>
</html>

Now I need a JavaScript function that returns me a DOM element with a specific identifier as a string from this text, for example:

function ExtractElementByIdFromString(HTMLString, IdString)
{
  var ExtractedElement = ???(HTMLString, IdString);
  return ExtractedElement;
}

Thus, the result of this function in this case will be:

<div id="main">
    <ul style="list-style-type: upper-roman">
        <li>&#196;pfel</li>
        <li>Birnen</li>
    </ul>
</div>

Is it possible?

+4
source share
2 answers

You can parse the HTML string with the native DOMParser :

var str = "<!DOCTYPE……………" // your HTML string

var doc = new DOMParser().parseFromString(str, "text/html")

Then just use the usual DOM methods:

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

, DOMParser , - innerHTML, - <script> , , CSS , ..

+4

, HTMLString , querySelector, id. - :

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;
}

jsFiddle.

+3

Source: https://habr.com/ru/post/1609841/


All Articles