How to get html element after append with pure JavaScript? - javascript

I found some JQuery solutions, but I am limited by school task restrictions to use pure Javascript, and I need to use specific early appended element that is still not in DOM for replacing by my CKEDITOR.
Code:
function newOption(){
...
mainUL = document.getElementById("myUL");
var inputA = document.createElement("input");
inputA.type ="text";
inputA.style = "margin-right: 45px";
inputA.name = "option[]";
inputA.id = inputID;
mainUL.appendChild(inputA );
CKEDITOR.replace(inputID).setData('Type anything you want ...');
...
}
By replacing my input with CKEDITOR will JS fail, because input, commonly, is still not in DOM. I tried to use
mainUL.innerHTML += "all elements like html text";
and this is working and will immediately insert elements into DOM, but I can't to use innerHTML, because it will remove old listeners (for example checked checkboxes that JS will set from checked to unchecked, what is my main problem due to I have to try using append DOM function).

Try changing the code to wrap the call to CKEDITOR.replace in a setTimeout:
setTimeout(function() {
CKEDITOR.replace(inputID).setData('Type anything you want ...');
},0).
This will allow the browser time to insert the element before trying to replace it.
And I assume that inputID has a valid value in it...

Related

How can I add new radio buttons without unchecking old ones? [duplicate]

I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
How can I get it to keep whatever has be enetered in the form and also add the new field to the end?
Setting innerHTML destroys the contents of the element and rebuilds it from the HTML.
You need to build a separate DOM tree and add it by calling appendChild.
For example:
var container = document.createElement("div");
container.innerHTML = "...";
document.getElementById("theform_div").appendChild(container);
This is much easier to do using jQuery.
Step One:
Add jQuery to your headers:
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
Step Two:
Append, don't replace, data to your DIV like this:
$("#theform_div").append("your_new_html_goes_here");
Don't use innerHTML to create the form elements. With innerHTML you're overwriting the old HTML with new HTML which will recreate all the elements. Instead you need to use the DOM to create and append the elements.
EXAMPLE
function addRadioElement()
{
var frm = document.getElementById("form_container");
var newEl = document.createElement("input");
newEl.type = "radio";
newEl.name = "foo";
newEl.value = "bar";
frm.appendChild(newEl);
}
The most correct way to do it without using a framework (like jQuery, Dojo, YUI) is:
var text = document.createTextNode('The text you want to write');
var div = document.createElement('div');
div.appendChild(text);
document.getElementById('theform_div').appendChild(div);
innerHTML, although supported by most browsers, is not standard compliant and - therefore, not guaranteed to work.
I would suggest using jQuery and its append function.

Add a link to a form with jQuery (userscript) in Firefox

I'm trying to add a search link to an online form with a userscript using jQuery. I don't work too much in firefox and I feel like things that would normally work in chrome don't in ff 9/10 times for me. But anyway... this needs to be with ff.
I'm taking the text from a <p> element and creating a search url out of it (or trying to). Right now this is the function I'm trying that should be doing it... but it's doing nothing, not even any errors in console
$(function() {
var companyName = $('p')[7]; // Element that contains the name text
var companyText = companyName.text(); // Retrieve the text from element
var mixRankUrl = $("<a></a>").innerHTML("Search Mixrank"); // Create an <a> element
mixRankUrl.href = 'https://mixrank.com/appstore/sdks?search=' + companyText; // Define the href of the a element
var sdkPara = $('label.control-label')[10]; // Where I want it to go
sdkPara.append(mixRankUrl); // Append the element
});
Also, whoever wrote the html uses hardly any ids, and most classes are assigned to 10 or more elements... so unless there's a better way, I'm sort of stuck using node selectors (which stay the same form to form).
The problem is that you try to use jQuery method on DOM element. Don't understand why you don't have any errors with your code.
For exemple : $('p')[7] return a DOM element while $('p').eq(7) return a JQuery object. So you can't use a jQuery method like text() on your DOM element. You need to deal with jQuery object.
For the same reason, you had a problem with the declaration of your label object and with the modification of the href attribute of your link.
Try like this :
$(function() {
var companyName = $('p').eq(7); // Element that contains the name text
var companyText = companyName.text(); // Retrieve the text from element
var sdkPara = $('label.control-label').eq(10); // Where I want it to go
var mixRankUrl = $('<a>',{
text: 'Search Mixrank',
href: 'https://mixrank.com/appstore/sdks?search=' + companyText
}).appendTo(sdkPara); // Append the element
});

Script not creating <a> element

I am trying to add a link to a page I cannot directly access the HTML on, aside from the footer. Using Javascript, I am attempting to use the createElement() method. I have successfully used the same process to create a link element in the header.
function createForgotPasswordLink(){
var pwlink=document.createElement("a")
pwlink.setAttribute("id", "forgotPssLink")
pwlink.setAttribute("href", "http://www.mysite.com/page.aspx")
pwlink.innerHTML("Forgot Password?")
document.getElementsByTagName("body")[0].appendChild(pwlink)
}
createForgotPasswordLink();
The only difference between the two scripts is that when making the link element, I appendChild() on the head not body and I do not set the innerHTML of the link element as I have done in the above a element. For some reason, the above code does not work. Even after removing line 5.
You are using the property .innerHTML like a method. Don't use parens, use an =. Also, I wouldn't bother setting the attributes, just set the property values directly. The code is more straightforward and easier to read:
function createForgotPasswordLink() {
var pwlink = document.createElement("a");
pwlink.id = "forgotPssLink";
pwlink.href = "http://www.mysite.com/page.aspx";
pwlink.innerHTML = "Forgot Password?";
document.body.appendChild(pwlink)
}

Extracting text from a HTML to be stored as a JS variable, then to be added to a separate HTML's element

Alrite, I have seen other Questions with similar titles but they don't do exactly what Im asking.
I have 2 x HTML documents, one containing my page, one containing a element with a paragraph of text in it. As-well as a separate .js file
what I want to do is extract this text, store it as a JS variable and then use jQuery to edit the contents of an element within the main page. This is the conclusion I came to but it didnt work as expected, im not sure if it is me making a syntax error or if i am using the wrong code completely:
$(document).ready(function(){
var c1=(#homec.substring(0))
// #homec is the container of the text i need
$(".nav_btn #1").click(function(c1){
$(".pcontent span p") .html(+c1)}
);
});
i know +c1 is most probably wrong, but i have been struggling to find the syntax on this one. thankyou in advance :D
var c1=(#homec.substring(0)) will throw an error because #homec is not a valid variable name, is undefined, and does not have a property function called substring. To get the html of an element with an id of homec, use the html method:
var c1 = $("#homec").html();
c1 should not be an argument of the click function because it is defined in the parent scope. +c1 is unnecessary because you do not need to coerce c1 to a number.
If you are trying to add content to the end of the paragraph, use the append method:
$(".pcontent span p").append(c1)
That means you should use this code instead:
$(document).ready(function() {
var c1 = $("#homec").html();
$(".nav_btn #1").click(function() {
$(".pcontent span p").append(c1)
});
});
P.S. Numbers are not valid ID attributes in HTML. Browsers support it, so it won't make anything go awry, but your pages won't validate.
Try this:
$(".nav_btn #1").click(function(c1){
var para = $(".pcontent span p");
para.html(para.html() + c1);
});
The JQuery text() function will allow you to get the combined text contents of each element in the set of matched elements, including their descendants. You can then use the text(value) function to set the text content of your target paragraph element. Something like this should suffice:
$(document).ready(function() {
var c1 = $("homec").text();
$(".nav_btn #1").click(function() {
$(".pcontent span p").text(c1);
});
});
See the JQuery documentation for more details on the text() function. If you need to capture the full structure of the other document, then try the html() function instead.

Add to HTML form without losing current form input information in Javascript

I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
How can I get it to keep whatever has be enetered in the form and also add the new field to the end?
Setting innerHTML destroys the contents of the element and rebuilds it from the HTML.
You need to build a separate DOM tree and add it by calling appendChild.
For example:
var container = document.createElement("div");
container.innerHTML = "...";
document.getElementById("theform_div").appendChild(container);
This is much easier to do using jQuery.
Step One:
Add jQuery to your headers:
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
Step Two:
Append, don't replace, data to your DIV like this:
$("#theform_div").append("your_new_html_goes_here");
Don't use innerHTML to create the form elements. With innerHTML you're overwriting the old HTML with new HTML which will recreate all the elements. Instead you need to use the DOM to create and append the elements.
EXAMPLE
function addRadioElement()
{
var frm = document.getElementById("form_container");
var newEl = document.createElement("input");
newEl.type = "radio";
newEl.name = "foo";
newEl.value = "bar";
frm.appendChild(newEl);
}
The most correct way to do it without using a framework (like jQuery, Dojo, YUI) is:
var text = document.createTextNode('The text you want to write');
var div = document.createElement('div');
div.appendChild(text);
document.getElementById('theform_div').appendChild(div);
innerHTML, although supported by most browsers, is not standard compliant and - therefore, not guaranteed to work.
I would suggest using jQuery and its append function.

Categories