Javascript .replace() method failing in IE8 - javascript

Why does this not work in IE8?
var accordion = $(this),
header = accordion.find(':header')[0],
titleHTML = header.outerHTML,
innerHTML = accordion.html().replace(titleHTML, '');
The header variable is populated, but .replace() does not find the string of HTML. It works in Chrome, FF etc but IE8 does not want to play.
I tried removing the element before building the innerHTML variable but that introduced more problems further down the execution path.
Can anyone shed any light on this?
EDIT
The rewrite worked with a bit of massage.
var accordion = $(this),
header = accordion.find(':header').first(),
titleHTML = header.prop('tagName'),
titleLabel = header.text();
header.remove();
var innerHTML = accordion.html();
Essentially the two main changes were to getting the first element with [0] was a bit flaky and indeed removing the element first was the way to go.

Try this
$(this).find(':header').first().remove();
It seems that's basically what you're doing, find any header elements, get the native DOM node of the first one, then getting the outerHTML, and replacing it in this, trying to remove it, and it seems like a strange way to do it.

Related

Can jquery manipulate a temporary document created with DOM?

The thing that I want to achieve is to manipulate a document created with DOM using jquery by passing a big html string. Consider the following example:
var doctype = document.implementation.createDocumentType( 'html', '', '');
var dom = document.implementation.createDocument('', 'html', doctype);
dom.documentElement.innerHTML = '<head><head><title>A title</title></head><body><div id="test">This is another div</div></body>';
This will create a new document in dom, with the content provided. Now I want to use jquery to append let's say a div inside the existing div.
$('#test',dom).append('<div> A second div</div>');
console.log(dom);
When I print the result in the console it seems that the innerHTML of the 'dom' has not changed. From the API documentation of jquery,http://api.jquery.com/jQuery/ more specific "jQuery( selector [, context ] )" function should allow this.
Since someone may argue about using the console to debug, I am providing below another part of code that does not work:
$('body').append($('#test',dom));
Tested in chrome and firefox and it does not work with the latest jquery library.
By changing the constructors and using the line below
var dom = document.implementation.createHTMLDocument("Test");
instead of the two lines originally introduced
var doctype = document.implementation.createDocumentType( 'html', '', '');
var dom = document.implementation.createDocument('', 'html', doctype);
everything works fine, even when setting the innerHTML directly!
It would appear that it is setting the entire HTML content through innerHTML that does not work.
From experimenting with your code, you'll notice that the following doesn't yield any result either:
dom.documentElement.getElementsByTagName('body')
And that dom.body is null. However, if you would construct the objects rather than to just set the innerHTML, both the above and the jQuery selectors will work:
dom.body = document.createElement('body');
dom.body.appendChild(document.createElement('div'));
console.log($('div', dom));
Yes its possible. You have to create secont instance of jQuery. Check this fiddle: http://jsfiddle.net/hDcUp/
var jq2 = jQuery(dom);

Adding Javascript variables to HTML elements

So, I have some code that should do four things:
remove the ".mp4" extension from every title
change my video category
put the same description in all of the videos
put the same keywords in all of the videos
Note: All of this would be done on the YouTube upload page. I'm using Greasemonkey in Mozilla Firefox.
I wrote this, but my question is: how do I change the HTML title in the actual HTML page to the new title (which is a Javascript variable)?
This is my code:
function remove_mp4()
{
var title = document.getElementsByName("title").value;
var new_title = title.replace(title.match(".mp4"), "");
}
function add_description()
{
var description = document.getElementsByName("description").value;
var new_description = "Subscribe."
}
function add_keywords()
{
var keywords = document.getElementsByName("keywords").value;
var new_keywords = prompt("Enter keywords.", "");
}
function change_category()
{
var category = document.getElementsByName("category").value;
var new_category = "<option value="27">Education</option>"
}
remove_mp4();
add_description();
add_keywords();
change_category();
Note: If you see any mistakes in the JavaScript code, please let me know.
Note 2: If you wonder why I stored the current HTML values in variables, that's because I think I will have to use them in order to replace HTML values (I may be wrong).
A lot of things have been covered already, but still i would like to remind you that if you are looking for cross browser compatibility innerHTML won't be enough, as you may need innerText too or textContent to tackle some old versions of IE or even using some other way to modify the content of an element.
As a side note innerHTML is considered from a great majority of people as deprecated though some others still use it. (i'm not here to debate about is it good or not to use it but this is just a little remark for you to checkabout)
Regarding remarks, i would suggest minimizing the number of functions you create by creating some more generic versions for editing or adding purposes, eg you could do the following :
/*
* #param $affectedElements the collection of elements to be changed
* #param $attribute here means the attribute to be added to each of those elements
* #param $attributeValue the value of that attribute
*/
function add($affectedElements, $attribute, $attributeValue){
for(int i=0; i<$affectedElements.length; i++){
($affectedElements[i]).setAttribute($attribute, $attributeValue);
}
}
If you use a global function to do the work for you, not only your coce is gonna be easier to maintain but also you'll avoid fetching for elements in the DOM many many times, which will considerably make your script run faster. For example, in your previous code you fetch the DOM for a set of specific elements before you can add a value to them, in other words everytime your function is executed you'll have to go through the whole DOM to retrieve your elements, while if you just fetch your elements once then store in a var and just pass them to a function that's focusing on adding or changing only, you're clearly avoiding some repetitive tasks to be done.
Concerning the last function i think code is still incomplete, but i would suggest you use the built in methods for manipulating HTMLOption stuff, if i remember well, using plain JavaScript you'll find yourself typing this :
var category = document.getElem.... . options[put-index-here];
//JavaScript also lets you create <option> elements with the Option() constructor
Anyway, my point is that you would better use JavaScript's available methods to do the work instead of relying on innerHTML fpr anything you may need, i know innerHTML is the simplest and fastest way to get your work done, but if i can say it's like if you built a whole HTML page using and tags only instead of using various semantic tags that would help make everything clearer.
As a last point for future use, if you're interested by jQuery, this will give you a different way to manipulate your DOM through CSS selectors in a much more advanced way than plain JavaScript can do.
you can check out this link too :
replacement for innerHTML
I assume that your question is only about the title changing, and not about the rest; also, I assume you mean changing all elements in the document that have "title" as name attribute, and not the document title.
In that case, you could indeed use document.getElementsByName("title").
To handle the name="title" elements, you could do:
titleElems=document.getElementsByName("title");
for(i=0;i<titleElems.length;i++){
titleInner=titleElems[i].innerHTML;
titleElems[i].innerHTML=titleInner.replace(titleInner.match(".mp4"), "");
}
For the name="description" element, use this: (assuming there's only one name="description" element on the page, or you want the first one)
document.getElementsByName("description")[0].value="Subscribe.";
I wasn't really sure about the keywords (I haven't got a YouTube page in front of me right now), so this assumes it's a text field/area just like the description:
document.getElementsByName("keywords")[0].value=prompt("Please enter keywords:","");
Again, based on your question which just sets the .value of the category thingy:
document.getElementsByName("description")[0].value="<option value='27'>Education</option>";
At the last one, though, note that I changed the "27" into '27': you can't put double quotes inside a double-quoted string assuming they're handled just like any other character :)
Did this help a little more? :)
Sry, but your question is not quite clear. What exactly is your HTML title that you are referring to?
If it's an element that you wish to modify, use this :
element.setAttribute('title', 'new-title-here');
If you want to modify the window title (shown in the browser tab), you can do the following :
document.title = "the new title";
You've reading elements from .value property, so you should write back it too:
document.getElementsByName("title").value = new_title
If you are refering to changing text content in an element called title try using innerHTML
var title = document.getElementsByName("title").value;
document.getElementsByName("title").innerHTML = title.replace(title.match(".mp4"), "");
source: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
The <title> element is an invisible one, it is only displayed indirectly - in the window or tab title. This means that you want to change whatever is displayed in the window/tab title and not the HTML code itself. You can do this by changing the document.title property:
function remove_mp4()
{
document.title = document.title.replace(title.match(".mp4"), "");
}

SVG: compact way to create slightly different elements?

I'm creating several elements which are almost identical paths, with a long list of co-ordinates. Is there a compact way to create one element, and to to make slightly different copies of it?
The elements are created by 'createElementNS'. The obvious (I think) answer is to clone the first element into a new element, and to set only the attributes in the second element which have changed. This works in Chrome and IE9, but not in FF4 or Opera.
Another obvious solution is just to copy the first element into a var, and to set the changed attributes in the var. This doesn't work in Chrome or FF.
I could possibly create a new element via createElementNS, and copy all the attributes in from the old element, but I don't know of a way to cycle through all attributes, which would help.
This is an example of the almost-working clone code:
obj = svgDocument.createElementNS(svgns, "path");
obj.setAttributeNS(null, "id", "pbox1");
...lots more attributes set
svgDocument.documentElement.appendChild(obj);
// now try to clone and copy:
var obj2 = obj.cloneNode(true);
obj2.setAttributeNS(null, "id", "pbox2");
...change a few obj2 attributes
svgDocument.documentElement.appendChild(obj2);
Any ideas?
Thanks -
Al
var templateElement = document.createElement(// create template element);
var firstElement = templateElement.cloneNode(true) // the true make sure it clones all child nodes
var firstElement.setAttribute()// change what you need
and so on for as many elements as you need.
aaah.. stupid typo on my part; sorry. The code I posted above was correct, but I didn't show the other clones underneath. On the final one, I put in var obj10 = obj.cloneNode() , leaving out the 'true'. It looks like FF4 and Opera got the right answer, and Chrome and IE9 copied all the attributes anyway.

Equivalent of "parentNode" in internet explorer

I wrote some code that modifies the images on a webpage. Works with firefox and safari. But tryingto get it to work with Internet explorer has got me stumped. What is the equivalent of "parentNode" in explorer? Or how does one trick it into working?
images = document.getElementsByTagName('img')
parms = {};
for (a=0;a < images.length;a++){
parent = images[a].parentNode; // <-- What to substitute for explorer?
parms[a] = {};
parms[a].bigsrc=parent.getAttribute("href");
parms[a].w_o = images[a].width;
parms[a].h_o = images[a].height;
parms[a].IsBig = false;
parms[a].loaded = false;
images[a].border=0;
parent.setAttribute("href","javascript:MakeBig('"+a+"')");
}
The problem is with the assignment of the parentNode to a var called "parent." This seems to be a reserved word in IE that breaks the code. Change the var name and it should work.
parentNode works fine in IE (except in certain cases, very likely irrelevant here). The error is almost certainly elsewhere in your code.
Are you expecting the parentNode to be an anchor? It looks like you're trying to just wrap the image in a link. If that's correct, what might work as an alternative is adding an onclick to the image itself, and setting a hand cursor. That could create the appearance of the image being a link without you having to care what the parentNode is.

This javascript works in every browser EXCEPT for internet explorer!

The webpage is here:
http://develop.macmee.com/testdev/
I'm talking about when you click the ? on the left, it is supposed to open up a box with more content in it. It does that in every browser except IE!
function question()
{
$('.rulesMiddle').load('faq.php?faq=rules_main',function(){//load page into .rulesMiddle
var rulesa = document.getElementById('rulesMiddle').innerHTML;
var rules = rulesa.split('<div class="blockbody">');//split to chop off the top above rules
var rulesT = rules[1].split('<form class="block');//split to chop off below rules
rulesT[0] = rulesT[0].replace('class=','vbclass');//get rid of those nasty vbulletin defined classes
document.getElementById('rulesMiddle').innerHTML = rulesT[0];//readd the content back into the DIV
$('.rulesMain').slideToggle();//display the DIV
$('.rulesMain').center();//center DIV
$('.rulesMain').css('top','20px');//align with top
});
}
IE converts innerHTML contents into upper case, so you probably are not able to split the string this way, as string operations are case sensitive. Check what the contents really looks like by running
alert(rulesa);
Andris is right. And that's not all. It'll also throw away the quotes in attributes.
It is completely unreliable to make any assumptions about the format of the string you get from innerHTML; the browser may output it in a variety of forms — some of which, in IE's case, are not even valid HTML. The chances of you getting back the same string that was originally parsed are very low.
In general: HTML-string-hacking is a shonky waste of time. Modify HTML elements using their node objects instead. You seem to be using jQuery, so you've got loads of utility functions to help you.
In any case you should not be loading the whole HTML page into #rulesMiddle. It includes a load of scripts and stylesheets and other header nonsense that can't go in there. jQuery allows you to pick which part of the document to insert; you seem to just want the first .blockbody element, so pick that:
$('#rulesMiddle').load('faq.php?faq=rules_main .blockbody:first', function(){
$('#rulesMiddle .blockrow').attr('class', '');
$('.rulesMain').slideToggle();
$('.rulesMain').css('top', '20px');
});
My IE debugger throws an error on your script when I click that button. On this line:
var rulesT = rules[1].split('<form class="block');//split to chop off below rules
IE stops processing the Javascript and says '1' is null or not an object
Don't know if you solve it, but it work's on my Ugly IE ... (its an v8)
Btw: It's me, or does pop-up widows wen open are really, really, really slowing down that platform ?

Categories