Error: Not allowed element when it is in JS - javascript

Just a quick validation question, I get:
document type does not allow element "div" here
And my code:
$('#wrapper').prepend('<div id="slider"></div>');
It's just a JS stuff, how do I handle this?

I can't think of any time you would get that error in the middle of a piece of JavaScript unless you are using XHTML, in which case the short answer is: Stop using XHTML, start using HTML 4 or 5.
The reason you get the error is described in the XHTML 1.0 specification:
In XHTML, the script and style elements are declared as having #PCDATA content. As a result, < and & will be treated as the start of markup
The latest version of the XHTML Media Types note provides work–arounds:
DO use external scripts if your script uses < or & or ]]> or --. DO NOT embed a script in a document if it contains any of these characters.
and
If you must embed the content, the following patterns can be used:
<style>/*<![CDATA[*/
...
/*]]>*/</style>
This is all rather a lot of effort, and just switching to HTML is a simpler option. Browsers are designed for HTML and their XHTML support is provided as an afterthought. If you get any benefits from XHTML it will be from using it with server side tools as part of your publishing process … and not many people are doing that.

Related

Why does a self-closed script tag not trigger errors?

The following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A</title>
<script type="text/javascript" src="./script.js" />
<script type="text/javascript">alert("This is skipped.");</script>
</head>
<body>
</body>
</html>
passes the validation test at W3C and Chrome does not display any Javascript errors on this page. However, the entire text <script type="text/javascript">alert("This is skipped."); is not parsed by the Javascript engine which just looks for the </script> tag even though it's self-closed. The file "script.js" is loaded, however.
In Chrome, Firefox and IE 11, this leads to this same behaviour.
Why is this? What is actually happening here?
The code you have is valid because you have an XHTML doctype. In XHTML any element is permitted to use the self-closing syntax (although it makes little sense for most of them).
If you were serving your document with an XML content type (Content-Type: application/xhtml+xml for example) then it would work in browsers too.
Since you are (presumably) serving the document with Content-Type: text/html, the browser will parse it as HTML.
The first script tag will be parsed (the / will be ignored or treated as an invalid attribute).
The second script tag will be parsed by the HTML parser as JavaScript (so it will be treated as text)
The first script end tag will be parsed (and close the script tag from (1))
Since the first script tag has a src attribute, the external script will be loaded and passed to the JS parser
The inline "JavaScript" (the second script tag) won't be passed to the JS parser because a script element can't have an external and inline script (so you won't get a JS error from it). It may be added, as text, to the DOM though.
Note that the use of the self-closing syntax for script elements is banned by appendix C because HTML parsers do not give the desired result. All in all, XHTML is far more trouble then it is worth 99%+ of the time, and you should stick to using HTML instead of XHTML.
The script element is generally used in two ways, to either contain code between the two tags of the script element or to include code. When it includes code it does not technically need the end tag for the script element.
The quickest way to test the code as actual XHTML (application/xhtml+xml) is to create a file with a .xhtml file extension and then open that file in Firefox. Gecko, unlike the two Webkit forks (Chrome and Safari) and Trident (IE) will actually break the page and instead show an XML parsing error message, other rendering engines will simply stop rendering at the point the XML parse error was encountered.
A few things about correctly handling script elements...
There is no such mime as "text/javascript", it's actually application/javascript.
Microsoft's IE doesn't understand JavaScript until IE9 and will simply not render JavaScript unless it's served with this non-existent weird mime "text/javascript". If you're building your own stuff 2014 or onwards simply ignore Internet Explorer 8 and older as their shares will be utterly negligible by the time you bring something to market.
Avoid putting script elements in the body element if you're trying to learn how to code clean and strict, it'll force you to organize things; ensure you use the defer="defer" attribute/value pair if you had been putting script elements in the body for performance reasons.
If you have a lot of scripts simply use a server scripting language like PHP to include() multiple files in a single file. You'll have to use Apache to enable PHP rendering in a *.js file and then you'll need to output the correct mime.
JavaScript Example
<script defer="defer" type="application/javascript">
//<![CDATA[
window.onload = function
{
alert('Hello World.');
}
// ]]>
</script>
Everything that I've mentioned can be seen at my website in my profile as I code as strictly as possible. Sure strict code takes longer though I end up with almost utterly no maintenance which saves me hordes of time in the long run.

How can I get the result from the JavaScript html page using HtmlUnit?

I'm now working on using a JavaScript html to do some tests. And I want to use HtmlUnit to access the page to acquire the running results on the JavaScript webpage.
And this page is here(for the page source, you can right-click mouse to see the source):
http://itec.hust.edu.cn/~zhangcw/javascript.html
what I want is to get the running result about the delay value "delay:xxx ms" calculated by
the JavaScript on that page. However, when I use HtmlUnit to capture the html, it always capture the original source of that page and doesn't contain the running result. My code is like this:
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("http://itec.hust.edu.cn/~zhangcw/javascript.html");
String source = page.asXml();
System.out.println(Source);
The source only contains the JavaScript source codes and html content, not the execution result by the JavaScript on the page. What I should do using HtmlUnit?
My Question is how can I use the HtmlUnit to get the JavaScript running result on the page?
Thanks for reading the text, tough for my English skill.
HtmlUnit has a JavaScript engine that is very sensitive to syntactical errors. So the fact that something works in a normal browser (Chrome, IE, FF, etc) doesn't mean that it will work on HtmlUnit.
I took a very quick look at the code and detected too many syntactical errors. I even run this through the w3c validator and found 10 errors. Here is just one example:
<button type="button style="
You're clearly missing a quote there.
And also some errors that the validator might not detect such as:
<text id= _delay>
You are missing the quotes and you have an extra space.
Finally, the most likely reason why the code is not working is that you defined it as HTML 4.01 Transitional and you added the HTML5 attribute onerror to the image. Furthermore, you've added a piece of JavaScript to that attribute and it happens to be the JavaScript that is not executing.
Fixing errors might help. However, it doesn't necessarily mean it will work after that.

can we use AJAX with XHTML?

Can we use AJAX for updating a XHTML page?
To connect the html page, we used to write:
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
document.getElementById("target").innerHTML=xhr.responseText;
}
}
However, we can't change innerHTML to innerXHTML, because AJAX doesn't accept it.
Yes, you can update XHTML pages using ajax. You still use innerHTML (or the DOM methods). The description of innerHTML in the HTML5 spec describes how XML vs. HTML should be treated.
Re the various DOM methods, some reading/reference material:
DOM2 Core
DOM2 HTML (which applies to XHTML documents as well)
DOM3 Core
HTML5 Web Application APIs
My first thought was "of course!". As T.J. Crowder points out, standards-compliant browsers which follow the spec should have no problem.
However, there does seem to be talk of some issues using innerHTML and maintaining well-formed XHTML markup in older versions of IE.
Keep in mind that this is old information. It may no longer be a problem.
http://www.stainlessvision.com/jquery-html-vs-innerxhtml (which uses innerHTML)
http://www.stevetucker.co.uk/page-innerxhtml.php
My experience has been to the contrary, i.e. using innerHTML to insert markup is not a problem.
The AJAX piece is really irrelevant here; the question is whether or not innerHTML can be trusted to preserve the integrity of the markup being inserted into the document.
My site linked in my profile is served entirely as XHTML served as actual XHTML, application/xhtml+xml. Clicking on 'Site Options' at the top-right will in example load content via AJAX.
Code is not text, do not use responseText, use responseXML.
Never EVER use innerHTML, it's a proprietary Microsoft JScript method that is not compatible with the DOM. Using it adds huge swathes of ambiguity to your code, JavaScript may see elements you've loaded via AJAX but probably won't.
Use importNode as I have, these are two different document owners and you have to use importNode to load content from different documents.

Will non-IE browsers use script inside a tag with type="text/jscript"?

I inherited an ancient codebase that includes pages with <script type="text/jscript"> -- yes, my life really does suck that much. The script appears to do nothing in modern, decent browsers (FF and Chrome, for a start) and I'm wondering if the stated script type is causing it to be ignored. I spent some time trying to figure out what's going on, and I see things like
As explained by JavaScript guru Douglas Crockford in his talk entitled The JavaScript Programming Language on YUI Theater, "[Microsoft] did not want to deal with Sun about the trademark issue, and so they called their implementation JScript. A lot of people think that JScript and JavaScript are different but similar languages. That's not the case. They are just different names for the same language, and the reason the names are different was to get around trademark issues."
on Wikipedia. So Javascript == JScript? But then, I see conflicting information, like this answer which seems to suggest that script that's declared as JScript will only run in IE.
So: can I just change the type tag and everything will work fine? Is there a simple process for conversion? If not, I may just scrap the whole thing and start over.
From HTML 5 chapter 4.3
7) If the user agent does not support the scripting language given by the script block's type for this script element, then the user agent must abort these steps at this point. The script is not executed.
That same chapter also says
If either:
the script element has a type attribute and its value is the empty string, or
the script element has no type attribute but it has a language attribute and that attribute's value is the empty string, or
the script element has neither a type attribute nor a language attribute, then
...let the script block's type for this script element be "text/javascript".
so I would just remove type="text/jscript" save a bit on bandwidth and live happily ever after.
So Javascript == JScript?
JScript is what Microsoft calls JavaScript
But then, I see conflicting information, like this answer which seems to suggest that script that's declared as JScript will only run in IE.
That doesn't conflict. It just means that other browsers don't recognise the mime type.
Browsers will ignore script elements with a type they do not recognise. text/jscript is non-standard and most browsers don't recognise it (Internet Explorer considers it an alias for text/javascript).
can I just change the type tag and everything will work fine?
Probably. The script might depend on other proprietary Microsoft—isms (such as document.all) or other non-standard behaviour (automatic id attribute to JS global conversion or treating CSS lengths that are missing a unit as pixels) though.
The other answer you linked to is completely incorrect. There are no differences between JScript and JavaScript. Changing the script type to "text/javascript" should work (unless the intent of the author was to force it so that only IE ran the script)
the type= requirements have been taken out of html5. I believe the proper xhtml code would be ...
<script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>
... but browsers did not follow the requirements of xhtml of forcing an error. Most web hosts keep the delivery of xhtml and html docs as MIME-type "text/html", not the "application/xhtml+xml" which should force an error if the xhtml does not validate.
HTML4 uses are variety of types ... http://www.w3.org/TR/html4/interact/scripts.html ... but browsers do not force html4 validation.
vscript, tcl don't have common support - we are talking about Javascript or any of the other names it gets as in becomes a more powerful language.
A bogus "type" attribute will definitely make scripts not work. The browser thinks you don't want it to run the script, basically.
Really, the "type" attribute is not necessary unless you definitely don't want the browser to run a script (which people do when their "scripts" are actually template bodies, or other data like that). You could either change all yours to "text/javascript" or just get rid of the attribute entirely.

HTML5 <script> declarations

Is it still necessary (or even good practice) when using HTML5 to declare the script type when using a script block?
e.g. <script type="text/javascript">
Plus what about using a CDATA block in the script for browser parsing?
e.g. // <![CDATA[ ... ~code here ~... // ]]>
Any help much appreciated.
The current draft of HTML5 doesn't require the type attribute for script tags.
Also the <![CDATA is not required in HTML5 (it was XHTML specific anyway).
Is it still necessary (or even good practice) when using HTML5 to declare the script type when using a script block?
HTML 5 defines text/javascript as the default, and you'd be hard pressed to find a browser that didn't treat it as such. So you can omit it.
Plus what about using a CDATA block in the script for browser parsing?
Pointless unless you are writing XHTML 5 and using characters such as < or & in the script (but you should almost always be using external scripts anyway).
The CDATA comments are for XML, so only applicable if you're serving your pages up as xml (which you shouldn't be if it's HTML5).
As for the type attribute, it's optional now in HTML5.

Categories

Resources