EDIT: This isn't happening because of the ajax call. I changed it to use a value from a TinyMCE component for fun and I get the same thing.
content = tinyMCE.get('cComponent').getContent(); //content at this point is <p>test</p>
valueToDisplay = content;
If I do:
jQuery(selector).html(valueToDisplay);
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p>
Has anyone ever seen this before using Firefox 3.6.10 and jQuery 1.4.2, I am trying to change a link text using the result from a jQuery ajax call.
I get the result expected from the ajax call:
function getValueToDisplay(fieldType){
var returnValue;
jQuery.ajax({
type: "GET",
url: "index.cfm",
async:false,
data: "fieldtype="+fieldType,
success:function(response){
returnValue = response;
}
});
return returnValue;
}
If I check the value at this point I get the expected value
console.log(returnValue) //output this --> <p>Passport Photo</p>
However when I use jQuery(selector).html to insert it inside of an existing anchor
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">Passport Photo</a></p>
I have been trying to figure out where that xmlns anchor is added but can't narrow it down to anything specific.
EDIT: I have tried forcing dataType:"html" in the ajax call...no change.
Your selector represents something that is, or is in an a tag.
A much more minimal version of your problem would be:
html:
<a id="test"></a>
js:
$('#test').html('<p>test</p>');
result:
<a id="test"><p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p></a>
Change things around so you aren't putting p tags in an a tag, or do the following:
$('#test').empty().append('<p>test</p>');
I would like to extend the answer, as of why is happening, and provide a workaround.
Doing a GreaseMonkey script i was trying to change the content of an element, perhaps not changing per se but adding more elements as the tag had only an IMG inside.
Original:
<a onclick=something><img src=url></a>
What i tried to do was to insert a DIV element that would wrap the already IMG and another new SPAN second child, so the objetive was to end up with this:
<a onclick=something><div><img src=url><span>text</span></div></a>
Using the innerHTML property it would be like this:
ANode.innerHTML = '<div>' + ANode.innerHTML + '<span>text</span></div>';
but instead i got:
<a onclick=something><div><a xmlns="http://www.w3.org/1999/xhtml"><img src=url><span>text</span></a></div></a>
Looking at the answers here did help a bit although there's no real explanation. After a while i noticed something that does not happens with the example in the question, which now i believe is the key to this issue. I was the same as jfrobishow thinking where was it happening, i thought there was something wrong concatenating the ANode.innerHTML.
Answering, at the original question, the part of narrowing it down to where does this happens, notice that the out-of-nowhere <A> was enclosing both the IMG and the new SPAN nodes, so this made me curious, the unwanted <A> was being added just before the DIV element was "built". So from this, the original example, and my following workaround you can notice that this happens when you insert a new BLOCK node inside an Anchor, as both DIV and P (original example) elements are BLOCK elements.
(If you don't know what i mean by BLOCK is from the display property of an element http://www.w3schools.com/cssref/pr_class_display.asp)
The obvious workaround is to replace the type of node you're inserting, to a non-block element, in my case the problem was the DIV i wanted, but of course it depends on the objective of your script, most of the things are there by design, i put a DIV because i needed it, so i fixed it turning that DIV into another SPAN ( which is an inline element) but i still needed to behave like a block element so put the style, this is what worked for me:
ANode.innerHTML = '<span style="display:block;">' + ANode.innerHTML + '<span>text</span></span>';
So, plainly, this problem is not from scripting (Javascript for me) but from style (CSS) stuff.
BTW, this happened at Firefox 3.6.18, notice this does not happens at Firefox 5.0.
The problem is placing block elements inside an anchor tag.
This is not valid HTML, even though most browsers will parse it fine.
You just need to use a <span></span> element inside the anchor, instead of a <div> or <p>.
This is happening because in your <html> you declared a XML Namespace (xmlns). If the xmlns anchor is not breaking anything, just leave it there.
Also, don't use async:false, make a callback function to be called on success.
EDIT: Actually that just fixed the issue with that particular value... it started happening on other values where it used to be fine.
Somehow this fixed the issue.
Changed
jQuery(selector).html(valueToDisplay)
to
jQuery(selector).html(
function(index, oldHtml)
{
return valueToDisplay;
}
);
According to the doc, if I read it right it should be doing the same thing as I am not using oldHtml in the function. (http://api.jquery.com/html/).
From the doc: "jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content."
Try changing dataType in your ajax call to "text"
Using .append() instead of .html() fixed the issue for me. Never seen this before today. Why is it adding the extra xmlns? I tried changing my dataType to "text" as well, but it didn't work. It was really messing up my CSS styles as well, but using .append() completely resolved the issue. Thanks!
UPDATE: I needed to completely replace the content of my div with the result of an .ajax() query. .append() by itself wasn't sufficient, as it would just add to the content, so I found another workaround:
First clear the div:
$("#myDiv").html("");
Then, append the content using .append():
$("#myDiv").append("My content");
It's not perfect, but it works.
Related
A button calls a JS function that loads a different PHP page asynchronously using jQuery load, and it will put the result in a errorReturn div.
<div id='errorReturn'></div>
<button onclick='trySomething()'>Click me</button>
<script>
function trySomething() {
var url = 'otherpage.php'
$('#errorReturn').load(url)
}
</script>
All is fine.
Since I want the user to see ALL the errors if the button is clicked multiple times, I wanted to APPEND that result to the same div.
I tried both
$('#errorReturn').append.load(url)
$('#errorReturn').append(load(url))
And they didn't work. Then I found the solution:
$('#errorReturn').append($('#errorReturn').load(url))
It works. Kind of :( It fills the errorReturn div, but it doesn't append to it. It simply overwrites it, as if I simply wrote
$('#errorReturn').load(url)
I should probably just take a break, but I cannot see what's wrong :(
EDIT: Since somebody flagged this as "answered in another question", the other question was using JS while I was explicitly asking for jQuery - plus the other answer generated a lot of fuss about adding HTML with possible XSS injection and I think the accepted answer here is way nicer and simpler to understand
load() always overwrites the content of the target element. To do what you require you could make the AJAX request and append the content manually. Try this:
<div id="errorReturn"></div>
<button id="add-content">Click me</button>
jQuery($ => {
$('#add-content').on('click', e => {
$.ajax({
url: 'otherpage.php',
success: html => $('#errorReturn').append(html)
});
});
});
Make a new <div>, .load() content into it, and .append() that.
$("#errorReturn").append($("<div/>").load(url));
You can of course also add styles etc. to the <div>, like for example a top margin to separate the individual errors.
I'm pretty new to JavaScript, and I'm trying to figure something out. I have a series of images within a table, and I'd like each image to display within a div element when you hover over one. The problem is, the code doesn't appear to be doing anything. I hover over the div element, and no changes are being made to the #bigdisplay element. If I replace the backgroundImage with a property such as color, it works completely fine. What am I doing wrong? This is the code for my div element.
<div id="image1" onmouseover="document.getElementById('bigdisplay').style.backgroundImage='url('images/Slideshow1.png')';">
/* ... */
</div>
If I must provide any other code from my site I will (although I don't believe any of it is relevant). Any help would be greatly appreciated! Thank you!
Your code is fine. I separated the js just to make it easier to read. Your problem is either you have no height to the div or your path is wrong
function test(){ document.getElementById('bigdisplay').style.backgroundImage=
'url("https://res.cloudinary.com/rss81/image/upload/gw.jpg")'}
html,body,div{
height:100%;
}
<div id="bigdisplay" onmouseover="test()">
test
</div>
You're not properly escaping the string in the attribute. Attach the listener in Javascript instead, rather than in HTML attributes (which is as bad as eval) and it'll be easier to read and write:
const bigdisplay = document.querySelector('#bigdisplay');
document.querySelector('#image1').addEventListener('mouseover', () => {
bigdisplay.style.backgroundImage = "url('images/Slideshow1.png')";
});
I think one problem is that you used single quote to quote 'images/Slideshow1.png'. But you used single quote also for 'url('images/Slideshow1.png')'. So there is a conflict. Try 'url("images/Slideshow1.png")'. A part for this I find better to define the event handler function in the js document linked to the html document.
So, I have this pretty complex ajax thing going.
It loads new html (including div tags and all) to show up on the page.
I included a 'more' link to load additional data.
This more link links to my javascript function. The 'more' link is located in a div, which I gave a unique id. The next time the load function is called, I use document.getElementById(the id).style.display="none"; to "remove" this div from the look of the page.
I set error traps for this, the div with that id is found without problems, but javascript fails to change my style property.
I tested alert(document.getElementById(the id).innerHTML); and that worked without problems - hence the title of the question.
So, does anyone have any ideas/do I need to offer more information? The main problem is that it doesn't throw any errors anywhere, yet it fails to complete the task I asked...
Here's a bit of code to go with it -
try
{
var myidthing = "morelink" + ContentStart.toString(); //the id is correct
var div = document.getElementById(myidthing);
if (!div)
{
}
else
{
div.style.display="none"; //this doesn't work, but doesn't raise an error
alert(div.innerHTML); //this works without problem
}
}
catch(theerr)
{
alert(theerr);
}
------------------------->EDIT<-------------------------
I'm incredibly sorry if I upset any people.
I'm also angry at myself, for it was a stupid thing in my code. Basically, I had a variable that stored the contents of a parent div. Then I (succesfully) removed the div using the removeChild() method. Then my code pasted the contents of that vaiable (including the div I wanted gone) back into the parent div.
I switched around the order and it works fine now.
Again, excuse me for this.
Throwing out a few ideas of things to look for:
You said the div is generated by javascript. Is it possible the div you are targeting is not the one you think you are? It could be you are targeting another div, which is already hidden, or obstructed... or maybe the innerHTML you are displaying goes with a different element than the one you intend to target. Put an alert or script breakpoint in the if(!div) case, also, and see if it's going down that path.
If the above code is only a stripped-down version of your actual code, check your actual code for typos (for example: style.display = "none;";)
Using the FireBug plugin for FireFox, inspect the target element after the operation completes, and make sure that the display: none appears in the style information. If not, use FireBug's debugger to walk through your javascript, and see if you can figure out why.
Use FireBug to break on all script errors, in case there is another error causing this behavior.
Try empty quotes instead of 'none' and see if that works?:
document.getElementById('element_id').style.display="";
Failing that, don't change the style, just add a class which hides the element.
Firstly, is there a way to use document.write() inside of JQuery's $(document).ready() method? If there is, please clue me in because that will resolve my issue.
Otherwise, I have someone's code that I'm supposed to make work with mine. The catch is that I am not allowed to alter his code in any way. The part that doesn't work looks something like this:
document.write('<script src=\"http://myurl.com/page.aspx?id=1\"></script>');
The script tag is referencing an aspx page that does a series of tests and then spits out something like so:
document.write('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">')
The scripts are just examples of what is actually going on. The problem here is that I've got a document.write() in the initial script and a document.write() in the script that get's appended to the first script and I've got to somehow make this work within JQuery's $(document).ready() function, without changing his code.
I have no idea what to do. Help?
With the requirements given, no, you can't use document.write without really hosing up the document. If you're really bent on not changing the code, you can override the functionality of document.write() like so and tack on the result later:
var phbRequirement = "";
$(function() {
document.write = function(evil) {
phbRequirement += evil;
}
document.write("Haha, you can't change my code!");
$('body').append(phbRequirement);
});
Make sure you overwrite the document.write function before it is used. You can do it at anytime.
The other answers are boring, this is fun, but very pretty much doing it the wrong way for the sake of fulfilling the requirements given.
picardo has the approach I would've used. To expand on the concept, take a read:
$('<script/>')
.attr('src', 'http://myurl.com/page.aspx?id=1')
.appendTo('body');
Alternate style:
var imgnode = $('<img alt="Second image for id 1"/>')
.attr('src', "image1.jpg");
$('#id1').append(imgnode);
Be sure to use the attr method to set any dynamic attributes. No need to escape special symbols that way.
Also, I'm not sure what the effectiveness of dynamically generating script tags; I never tried it. Though, it's expected that they contain or reference client-side script. My assumption is that what page.aspx will return. Your question is a little vague about what you're trying to do there.
jQuery has a ready substitute for document.write. All you need to use is the append method.
jQuery('<img src=""/>').appendTo('body');
This is fairly self-evident. But briefly, you can replace the with whatever html you want. And the tag name in the appendTo method is the name of the tag you want to append your html to. That's it.
picardo's answer works, but this is more intuitive for me:
$("body").append('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">');
Also, for the script part that is being inserted with document.write(), check out jQuery's getScript() function
function DeleteData(ID)
{
var ctrlId=ID.id;
var divcontents=document.getElementById(ctrlId).innerHTML;
var tabid=ctrlId.replace(/div/,'tab');
var tabcontents=document.getElementById(tabid).innerHTML;
alert(document.getElementById(tabid).innerHTML);
document.getElementById(tabid).innerHTML="<TBody><tr><td></td></tr><tr><td></td></tr><tr><td></td></tr></TBody>";
document.getElementById(ctrlId).innerHTML='';
}
I am trying to replace the Table with empty table but
document.getElementById(tabid).innerHTML="<TBody><tr><td></td></tr><tr><td></td></tr><tr><td></td></tr></TBody>";
this line is causing Unknown Runtime Error
You can't set value to a table's innerHTML, you should access to child cells or rows and change them like that :
document.getElementById(tabid).rows[0].cells.innerHTML = 'blah blah';
For more info/example : Table, TableHeader, TableRow, TableData Objects
In IE8, you cannot change the innerHTML of an object when the code that attempts that is fired from within the object.
For example:
<span id='n1'>
<input type=button value='test' onclick='DoSomething(this);'>
</span>
with the following code tucked in some remote corner of your document:
<script type='text/javascript'>
function DoSomething(element)
{
document.getElementById("n1").innerHTML = "This is a test"
}
</script>
This will fail with the error unknown runtime error. I believe it has to do with the fact that you're trying to replace the HTML code which fired the current line of execution. The onclick event is part of the code being replaced by the DoSomething function. IE8 doesn't like that.
I resolved my issue by setting a timer event for 250 milliseconds, such that the function called at the end of the 250 milliseconds replaces the span's innerHTML.
I find out that in IE8 some elements are in readonly: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.
Therefore if you try to set innerHTML for these elements IE8 notify alter with Unknown Runtime Error.
More details here: http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx.
The simplest way is to convert read-only elements to div element.
I had the same issue but my error was because I was inserting a p tag directly underneath a p element as in:
document.getElementById('p-element').innerHTML = '<p>some description</p>';
I don't really see how this is HTML format error; seems more like another IE8 bug.
Great, I had the same situation with setting the innerHTML. When I read this I realised that one of the elements was a TR and one was a TD and the TD was working.
Changing the code so that they're both TDs fixes it, which means that it is a rather non-obvious problem caused by the structure of tables.
Presumably it throws the DOM awry when I start changing table rows since it can't store the table as an array any more.
I'm sure IE could give a more informative error message since it can't be that uncommon for the DOM to change on the fly and it seems strange that this would only throw an error for tables.
Ohh yes - remember that the HTML structure has to be valid.
I tried loading an entire page into a <p> tag - it failed (obviously), changing it to a <div> tag solved my problem!
So remember the HTML structure!
why it happend in IE...
case scenario:
Javascript unknown runtime error in IE while accessing Div inside Div to add ajax contents.
solution:
dont ever place nested divs in between the form tags to play with there contents .. :)
When using YUI try to use
Y.one('#'+data.id).setContent(html);
instead of:
Y.one('#'+data.id).set('innerHTML' , html);
If you need to set innerHTML to "" (empty string) then you can use removeChild instead
This is not a Big issue, since i faced same problem few days ago and the reason this error
occurs in ie is that - There exists an error in our html format or you are using an element other than <td> to replace innerHTML ie use only, dont use tables,divs to replace innerHTML.
SwapnilK