Question

When I'm editing HTML in the ace editor, is there a way to query that HTML in a simple way? With selectors?

[fake-html-dom].querySelectorAll("A").length

I read that when you use jQuery $('<html code>') the html gets inserted to the real DOM, I want to avoid actually running the HTML it in the window/iframe.

Would also be nice to be able to modify the found elements in the editor directly (like custom highlighting).

Was it helpful?

Solution

you can create a fake html document object like this:

var docImpl = document.implementation;
var fakeDoc = docImpl.createHTMLDocument("myhtml"/*it is just a title*/);

as you use a Ace html editor first you should read the html string from the editor, then extract the body content and finally insert it to the fake body. these are your steps to take:

//Ace usually uses ace_text-layer as the classname for the html string part
var htmlContent = document.querySelector(".ace_text-layer").innerText;
//you can also change this part if it didn't work, depends on your Ace version

now you should extract the body content, if it has <html> or <body> tags in it:

var pattern = /<body[^>]*>((.|[\n\r])*)<\/body>/im;
var array_matches = pattern.exec(htmlContent);
var extractedContent = array_matches[1];

then insert it to the fake body

fakeDoc.body.innerHTML = extractedContent;

and finally do any desired query you might need:

fakeDoc.querySelectorAll("A").length
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top