Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XHTML DOM manipulation with jQuery

I'm using Firefox 3.5. My doctype is XHTML 1.0 Strict. Let's say I want to insert an image into a div with id "foo"; then I might try:

var foo = $('#foo');
foo.html('<img src="bar.gif" />');

This does indeed add the image. But I noticed that this was causing some odd behavior later in the document, which I suspected might be due to XHTML breaking. Sure enough, using the Web Developer tool for Firefox, I checked the generated source and was horrified to find that after the script runs, I have:

<div id="foo"><img src="bar.gif"></div>

Where did the trailing slash on the img tag go!? Searching around, I found that this isn't a jQuery-specific problem: The pure JavaScript code

document.getElementById('foo').innerHTML = '<img src="bar.gif" />';

produces the same results. So, what should I do? I should note that using the expanded form

<img src="bar.gif"></img>

does not affect the result. How do I insert strictly valid XHTML into my document with JavaScript?

like image 573
Trevor Burnham Avatar asked Aug 03 '09 20:08

Trevor Burnham


People also ask

Is jQuery used for DOM manipulation?

jQuery was created in 2006 by John Resig. It was designed to handle Browser Incompatibilities and to simplify HTML DOM Manipulation, Event Handling, Animations, and Ajax.

Does jQuery make DOM manipulation faster?

jQuery is a wrapper that normalizes DOM manipulation in a way that works consistently in every major browser. It's fully reasonable for it to perform 25x slower than direct DOM manipulation.

What are DOM manipulation methods?

The DOM Programming Interface The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML elements are defined as objects. The programming interface is the properties and methods of each object.


2 Answers

This is a little bit of a shot in the dark, and I am not sure whether this could be the cause, but are you sure that you are serving XHTML and not just standard HTML with XHTMLs syntax. That is: is the MIME type of the document the default text/html or is it application/xhtml+xml?

I read the following article recently, and the problem you are having would make perfect sense to me if the document wasn't actually being treated as XML by the browser (and therefore it was removing the erroneous XHTML style slashes for not conforming to the MIME type)...

http://www.xml.com/pub/a/2003/03/19/dive-into-xml.html

Just a thought.

like image 176
olive Avatar answered Oct 06 '22 00:10

olive


Try this instead:

var image = document.createElement('img');
image.setAttribute('src', 'bar.gif');
foo.appendChild(image);
like image 38
Chase Seibert Avatar answered Oct 05 '22 23:10

Chase Seibert