configuring my code to append to child instead of innerHTML - javascript

I have this code I wrote
Currently it uses innerHTML to write to the page with a forloop. However, I noticed that instead of writing everything. It just writes the last element in the array.
I searched and saw that I have to use the DOM to get this done as innerHTML will ALWAYS destroy instead of replacing. So I wrote this
function print(message) {
var mydiv = document.getElementById("box");
mydiv.appendChild(document.createTextNode(message));
}
To go inside my code and replace the innerHTML line. However, this doesn't seem to work. Can anybody help me getting it running?
by "this doesn't seem to work" i mean that the code won't append to the child of box. so my text will not be inserted into the element with the 'box' ID.
What i want to happen is just like in my codepen where i used innerHTML but instead of each only the last element in the array showing up, i want them all to show up
edit:
okay updated the codepen. seems the code I posted on this page kinda works. but it doesn't seem to go in the right place. if you check the codepen and add some text and scroll down you can see it doesn't fit into place

Change the print function in this way:
function print(message) {
var html = document.getElementById("box").innerHTML;
document.getElementById("box").innerHTML = html + message;
}
http://codepen.io/anon/pen/bwBOdq

Related

Click event added to appended html; element not working as anticipated

OK I am sure I am doing something simple fundamentally wrong but am unable to resolve this issue on my own. I have tried googling and searching this forum and reading through the relevant parts of the jquery documentation.
If you need any further information please let me know. Many thanks in advance.
What I am trying to do:
I have a table showing details of various tests at the bottom of which I have a button to ad a new test. As each test comprises several rows of the table I have a template in a hidden div which I have cloned and appended to the live table. I am the using jquery to add appropriate classes and ids based on a variable integer for the sake of uniqueness. I am also attempting to add a click event to an image within one of the table cell to delete the rows relating to that particular test.
My current function
function newTest(sampleID){
var testID = $("#testCount").val();
$("#newTest tr").clone(true)
.addClass("test"+testID)
.appendTo("#testsTable"+sampleID);
$(".newdelbox:first")
.attr("id","testDelete"+testID)
.addClass("delbox")
.removeClass("newdelbox");
$(".test"+testID).on('click',"#testDelete"+testID,delSample(testID));
testID++;
$("#testCount").val(testID);
}
What I need to happen
Function to be called when image is clicked.
What is happening
Function is called only when script is assigned (not clicked). Function will not subsequently run when clicked. I am seeing no errors within the console.
What I have tried
chained to preceeding code:
.click(delSample(testID));
.on("click",delSample(testID));
.bind("click",delSample(testID));
As new line within function:
$(".test"+testID).on('click',"#testDelete"+testID,delSample(testID));
document.getElementById("testDelete"+testID).onclick(delSample(testID));
document.getElementById("testDelete"+testID).addEventListener("click",delSample(testID),false);
try this:
.click(function(){
delSample(testID);
});
OR
.on("click",function(){
delSample(testID);
});
i do not know of your html but i supose something like
.on("click",function(){
var current_id = jQuery(this).attr('id');
delSample(current_id);
});
just locate your id

Javascript create element and add HTML

say for instance i have the following line:
var arrowBase = document.createElement('div')
Now within this div tag i want to add some HTML (i.e text).
Then i tried the following:
arrowBase.innerHTML('hello');
However this does nothing:S
i have also tried: arrowBase.HTML('hello');
But once again without any result
I know is that rather simple but in my search i could'nt find the answer hope someone is able to help me out here
Read the docs, it is not a method.
arrowBase.innerHTML = 'hello';
arrowBase.textContent = "HELLO"
also does the same thing but only text can be specified. Whereas in innerHTML html tags can be specified along with the text.

Submit form and return result to same page with javascript

Im trying to write a small js script that will let a user input a string of text and then output it wrapped in some html to the page.
I know how to do this with php, but it seems a little bit of an overkill for such a simple action, plus im always keen to learn something new.
I was playing around using document.myform.submit(); but i wasnt sure how to submit the form value to a variable and then output that var to the screen using document.write();
Any ideas how i would do this ?
Ive created a jsfiddle of the problem here - http://jsfiddle.net/pudle/axcLz/
There are many ways to do it. Here is the code that shows one of them:
document.getElementById("myform").onsubmit = function (event) {
var link = document.getElementById("mylink");
var textField = document.getElementById("text");
link.href = textField.value;
textNode = document.createTextNode(textField.value);
if (link.hasChildNodes()) {
link.removeChild(link.lastChild);
}
link.appendChild(textNode);
event.preventDefault();
};
jsfiddle: http://jsfiddle.net/TMJGH/5/
I added an id attribute to the a element to make things easier.
First line says that we want to change the function that handles "onsubmit" event in our form and then we define that function. The "event" argument is used only to call .preventDefault() in the last line which basically means that we don't want the form to be actually submitted.
We need to get access to DOM elements in the javascript code, so I used document.getElementById. Then I set the href attribute to the value of the textField. To change the actual link text I created a new text node with the value of the textField (it is possible to use textNode.innerHTML but that won't escape HTML code if someone inserts it in the text field). Then I check if our a element already has some text in it - if yes, it has to be removed. Finally I append the text element as a new child to our a element.
If you want to append more HTML nodes inside a node you can easily create them with document.createElement('element name') and append them to link. I also have to mention that jQuery makes playing with DOM a lot easier.

Problem with jQuery - error when trying to find 2 tags

I have the following DOM structure:
/*:DOC += <div id='testDiv' class='testDivClass'><div id='innerTestDiv'></div></div><span id='testSpan' class='testSpanClass'><span id='innerTestSpan'></span></span>
Now I tried to run jQuery select against them as follow. The first one returned alright, but the second one failed:
// works
var result = $('#testDiv')[0];
alert(result.id);
// failed: id is null or not an object
var result2 = $('#testSpan')[0];
alert(result2.id);
I tried selecting id instead of class and got the same results.
My question is: how can I get the second select to work? Is there some sort of invisible iterator/pointer in jQuery which I need to reset to the beginning of the DOM before the second select?
Thanks.
EDIT: Ok this is the official "does not work" version. testDiv matched, but testSpan did not, hence I got an error saying id is null or not an object error in the second alert.
UPDATE: I did a test by swapping testDiv and testSpan in the html. Now BOTH select failed.
UPDATE2: I have changed the html back to what it used to look like. I'm using JsTestDriver to write up the test, but it is actually not calling anything at the moment. The actual html looks messier than this (more nested tags). I'm trying to get this simplified version to work first. It appears that jQuery was able to get into the first select, whether it'll be span or div, but couldnt get out of it to do the second select. I've replaced jQuery.js and jsTestDriver.jar to no avail.
Thanks.
The .className selector matches by class, not ID.
Therefore, $(span.testSpan) won't match any elements.
You need to change it to $('span.testSpanClass') ot $(span#testSpan') (using the #id selector, which matches ID).
For more information, read the documentation.
I don't know why, but for me your code worked well.
I added $(document).ready(function() { before that code, and when I opened the test page, the alert box showed up perfectly, both of them! I don't know when do you want this alert box showed, but if it is when visitor open the page, just add that code. Otherwise, add
function objectid() {
var result = $('#testDiv')[0];
alert(result.id);
var result2 = $('#testSpan')[0];
alert(result2.id);
}
That code worked well for me, too.
PS: Sorry if you don't understand my bad english.
More than likely, there is something else wrong with the HTML you're actually using. Since you're posting only a tiny bit of the html, we can't actually test your problem. Post the entire page, or at least the smallest piece of it that actually has the problem when you run your test.
I tested the jQuery code you reported on JS Bin, and the code worked fine. As the code is very basic, I don't think the problem is caused by the version of jQuery used.
What I ended up doing is wrapping the entire html with a div or span tag. I found that jQuery could not get out of a div/span tag once it gets into one (in my above example), so I just make it to go into a div/span tag once.
Not sure whether this is a patch or ugly fix, but it solved my problem for now.
Thanks for all the help!
Use "#" to select by id, use "." to select by class...

Javascript getElementById - reading works, altering doesn't

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.

Categories

Resources