Parsing invalid HTML with jQuery, without adding to the DOM?

I am working on a jQuery plugin that uses an HTML template. End users can go through a template that looks at the simplest level:

<template>
   <img src="/images/image_{field_id}.gif">
</template>

The template is supposed to be commented out, so the browser will not try to render anything. My code simply extracts the inside of the comment as text, and then uses jQuery to parse it in the element tree. Then I make specific replacements.

I remember reading that jQuery just uses the DOM to parse HTML, for example. when you just do

var x = $(html_string);

jQuery actually just adds it to the DOM to get the elements. The simplest action above will not do anything (until I actually added xit somewhere in the DOM), but this code causes the browser to try to load the image target, even if I never add it to the DOM. Here is a simple demonstration of this effect in action: http://jsfiddle.net/b5HGU/

So basically - is there a way to solve this problem? Can you create an "image" element with a well-known tag srcusing jQuery, but don’t load the image until you actually add it to the real DOM?

, , , jQuery DOM. , , , , jQuery, , . XML. , - , .

+5
2

$.parseXML, - .

, .

+3

, . - html jquery , .. , .

var parser = new DOMParser();
//i assume your html-string is in resp variable
var doc = parser.parseFromString(resp, "text/html");
// here just css-select your element with standard method
var div = doc.querySelectorAll('#mydiv');
// then you can wrap this element with jquery and do what you want
var $div = $(div);

, .

0

All Articles