user1580348
user1580348

Reputation: 6051

Extract element by ID from string?

I have a string which 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 which gives me back a DOM element with a specific ID as a string from this text, for example:

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

So the RESULT of this function in this case would be:

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

Is this possible?

Upvotes: 13

Views: 13120

Answers (2)

Teemu
Teemu

Reputation: 23396

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.

Upvotes: 4

Touffy
Touffy

Reputation: 6561

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.

Upvotes: 22

Related Questions