Copy Divs using Javascript - javascript

I have 2 diferent divs: [Div1] and [Div2].
My goal is that when i click on some event, i want [Div1] to be the exactly the same as the [Div2].
I used this code:
document.getElementById("div1")=document.getElementById("div2");
This is a javascript error and i dont know how to do anything like this.
I cant copy every element cuz those might change based on the users actions.
I found something about cloning a node but i couldn't put it to work.
Any sugestions?

Well depending on what you mean by "exactly the same" (sharing the same reference? duplication of values?), you might want to try cloning:
Try:
var node = document.getElementById("div2");
var node2 = node.cloneNode(true); //creates deep clone with events you can do something with
///Or you could just copy the markup over
document.getElementById("div1").innerHTML = node2.innerHTML;

Use jquery instead; when the user clicks the button/any action, use the following snippet:
$("div1").html($("div2").html());

Related

how to get tinyMCE text without using id

I have a am working on project where i load a lot of tinyMCE editor instances dynamically. Do not have access to element id, because user has a possibility to add new editor instance.
Previously when I was using regular textfields, so I was looping through all of them and doing something like this:
var obj = {
$(this).find('.mytextfieldselector').val()
}
problem is, that when I try to find tiny mce like this:
$(this).find('.mce-tinymce').getContent();
It doesn't work.
Is there any solution?
TinyMCE maintains an array of all editor instances on a page via tinymce.editors - it returns an array.
Here is a TinyMCE Fiddle that shows how to use it to iterate over all the editors and collect their content:
http://fiddle.tinymce.com/migaab/1
Today I found a solution. It was much simpler than I thought.
Loop through all the divs you have.
First take attribute 'id' of your editor using jquery. Then use tinyMCE.get(id).
it would be something like this:
$(this).find('.yourDivSelector').each(function() {
var currentEditorId = $(this).find('.yourTinyMCEEditorSelector').attr('id');
var textAreaValue = tinyMCE.get(currentEditorId).getContent();
//Here do what you want wit textAreatValue
}
tinyMCE.activeEditor.getContent()

Greasemonkey, replace every occurence of string every second

i try to figure out a greasemonkey script that replaces every onmousedown on a site with an ondblclick. And i want it to constantly update, like every 1,5 Seconds, because the page refreshes using AJAX.
This is the script i came up with, but it doesn't seem to be working.
window.setInterval(document.body.innerHTML= document.body.innerHTML.replace('onmousedown','ondblclick');,1500);
The page it should work with is internal use only. But a good example would be the google search, where onmousedown is used for the links of the results to swap out the URL before you click it.
I also tried it without the semicolon after the document.body.innerHTML.replace.
I'm really new to JavaScript, but since i'm the only one in the company who can code, this one is stuck with me.
Any help would be appreciated.
Also, a small "side question"
Do i have to use #exclude, or is it enough to only use #include internal.companysite.tld* so it will only work on this site ?
A direct answer: you need to supply a function to setInterval - and it's best to set a variable so that you can later cancel it with clearInterval() if necessary.
function myF(){document.body....;}
var myIntv = setInterval(myF, 1500);
You could also do it using an anonymous function in one line as you're trying to do... do that this way:
var myIntv = setInterval(function(){document.body....;}, 1500);
I wouldn't suggest this as the solution to your problem. What it sounds like you want to do is manipulate the active DOM - not really change the UI. You likely need something like this:
var objs = document.getElementsBy__(); // ById/ByName/etc - depends on which ones you want
for (var i in objs){objs[i].ondblclick = objs[i].onmousedown;objs[i].onmousedown = undefined;} // just an example - but this should convey the basic idea
Even better, if you can use jQuery, then you'll be able to select the proper nodes more easily and manipulate the event handlers in a more manageable way:
$(".class.for.example").each(function(){this.ondblclick = this.onmousedown;this.onmousedown = undefined;}); // just an example - there are multiple ways to set and clear these

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"), "");
}

javascript copying element value, where element name has a period

If an html element id has no period in it, then copying between elements is of course trivial, e.g.:
var theForm = document.paymentForm;
theForm.BillStreet1.value = theForm.ShipStreet1.value;
I've got a case where I need to have period in my ids, namely id="bill.street1" and id="ship.street1", and the following doesn't work :-(
theForm.bill.street1.value = theForm.ship.street1.value;
Can you please let me know how to handle the period? Does jquery make this simpler?
jQuery makes everything simplier by using css selectors to access elements. However, if you don't want to use jQuery, you can access the element this way, I believe.
theForm['bill.street1'].value = theForm['ship.street1'].value;
I haven't tested this, but it should work because periods are an alternate method to access an array, iirc.
Be sure to use theForm['bill.street1'].value = theForm['ship.street1'].value;
and not theForm.['bill.street1'].value = theForm.['ship.street1'].value;. The extra periods make the format invalid, in the same way using array.[2] instead of array[2] would invalidate it.
theForm['bill.street1'].value
theForm['ship.street1'].value

Javascript & HTML Getting the Current URL

Can anyone help me. I don't use Client-side Javascript often with HTML.
I would like to grab the current url (but only a specific directory) and place the results between a link.
So if the url is /fare/pass/index.html
I want the HTML to be pass
This is a quick and dirty way to do that:
//splits the document.location.href property into an array
var loc_array=document.location.href.split('/');
//have firebug? try a console.log(loc_array);
//this selects the next-to-last member of the array.
var directory=loc[loc.length-2]
url = window.location.href // Not particularly necessary, but may help your readability
url.match('/fare/(.*)/index.html')[1] // would return "pass"
There may be an easier answer, but the simplest thing I can think of is just to get the current URL with window.location and use some type of parsing to get which directory you are looking for.
Then, you can dynamically append the HTML to your page.
This may get you started:
var linkElement = document.getElementById("whatever");
linkElement.innerHTML = document.URL.replace(/^(?:https?:\/\/.*?)?\/.*?\/(.*?)\/.*?$/i,"$1");

Categories