Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
user1580348 Avatar asked Oct 01 '15 18:10

user1580348


People also ask

How do I grab an element by ID?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

How do you find the value of an element by ID?

HTML DOM Document getElementById()The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.

How will you retrieve an element with the ID first?

You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

Can I use document getElementById in node?

how can I use document. getElementById() in nodejs ? Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. It can also be configured to use full (non-headless) Chrome or Chromium.


1 Answers

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.

like image 129
Touffy Avatar answered Nov 10 '22 00:11

Touffy