appendChild is not a function - what am I doing wrong? - javascript

I know this is a very common error, but I just can't figure out why this isn't working.
I want to change the value of a span dynamically. Simple, right? I've tried $span.innerHTML = "text" and $span.innerText = "text", which do nothing, but don't throw any errors. My most recent attempt looks like this:
var $resourceSpan = $("#divname"+dynamic_variable);
var stringVar = functionThatReturnsString();
while( $resourceSpan.firstChild ) {
$resourceSpan.removeChild( $resourceSpan.firstChild );
}
var textNode = document.createTextNode(stringVar);
$resourceSpan.appendChild( textNode );
Does anyone know why I'm throwing this error? Thanks

You are dealing with jQuery object, methods like removeChild() and appendChild() belongs to dom element not to the jQuery object.
To remove all contents of an element you can use .empty() and to set the text content of an element you can use .text(), but using .text() will replace existing content so in your case you can just use
var $resourceSpan = $("#divname" + dynamic_variable);
var stringVar = functionThatReturnsString();
$resourceSpan.text(stringVar);

Did you wanna do somethin like this?
<html>
<head>
<title>STACK OVERFLOW TESTS</title>
<style>
</style>
</head>
<body>
<span>HI, IM SOME TEXT</span>
<input type = 'button' value = 'Click me!' onClick = 'changeText()'></input> <!-- Change the text with a button for example... -->
<script>
var text = 'I AM THE NEW TEXT'; // The text to go in the span element
function changeText(){
var span = document.querySelector('span');
span.innerHTML = text;
}
</script>
</body>
</html>

Related

How can change div textContent without use getElementsByName or getElementsById?

How can change div textContent without use getElementsByName or getElementsById?
I have a code like this :
function get_up_vote_text() {
var up_text=document.createElement('div');
up_text.setAttribute('name','up_text');
up_text.textContent='152';
return up_text;
}
And I want update "up_text" value in the following function (without using getElementsByName or getElementsById) :
function get_up_vote() {
var up = document.createElement('div');
up.setAttribute('name','up');
up.onclick=function () {
var temp=get_up_vote_text();
//I want write some code here to update "up_text" value
}
return up;
}
You could use this object :
up.onclick=function () {
var temp=get_up_vote_text();
this.textContent="new text content";
}
OR also from event using e.target :
up.onclick=function (e) {
var temp=get_up_vote_text();
e.target.textContent="new text content";
}
Hope this helps.
you can use jquery for it, use these tags on your HTML page
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
then if your div has a id = divID simply use $("#divID") to get the div you want

Appending a div element using javascript

I am new to jQuery and I am practicing appending div elements. Here is my code:
<!doctype html>
<html lang="en">
<head>
<title>Div Id</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<script>
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("This is a first division");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
</script>
<body>
<div id="div1">This is a second division.</div>
</body>
</html>
Output would be:
This is a second division.
But as per my implementation the output should be
This is a first division
This is a second division.
I am not able to figure where it is going wrong. Please someone help me out with this.
Thanks in advance.
onload is a property of the window object, not the document.body object.
This works:
window.onload = addElement;
actually it works.... try to move your javascript in the head of you html file
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("This is a first division");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
<div id="div1">This is a second division.</div>
$('#div1').before('<div id=div0>This is a first division</div>')
demo
If you want Jquery it is as simple as this.
If you want to use jQuery you can check this fiddle:
$('body').prepend('<div>This is a first division</div>');

add color dynamically to added text

i am working on this example of appendChild() method.but the difference is here i am trying to add more text to a div dynamically.that was all right.but the hard part is the text i want to add will be red in color.how can i do that?
i tried
text.setAttributes('color',"red");
But it didn't work.so,how this task can be done??please help,thanks!!!!
the full code is given below............
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function create_text(){
var mydiv = document.getElementById("mydiv");
var text = document.createTextNode(" New text to add.");
mydiv.appendChild(text);
}
</script>
</head>
<body>
<button onclick="create_text();">Create Text Node</button>
<div id="mydiv">Welcome, here is some text.</div>
</body>
</html>
You would normally have to use CSS properties, however, text nodes cannot have CSS properties applied to them. You therefore need another container element:
You can choose any container element you wish, e.g. div, span, etc. It just needs to be capable of containing a text node. Having an element then allows us to access the styles property and set various styles (the color attribute in your case).
→ jsFiddle
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
container.style.color = "red";
mydiv.appendChild(container);
}
Further note:
the order of the color assignments and calls of appendChild is arbitrary. The following would also be possible:
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
mydiv.appendChild(container);
container.style.color = "red";
}
mydiv.style.color = 'red';
or just in css
#mydiv { color: red; }
if you have other elements inside the div that you don't want to be red, you'd need to wrap the new text in a span or div or another element before appending.
with jquery this would be super easy:
$('#mydiv').append('<span style="color:red">this is new text</span>');
If that's everything in your div, you could try
document.getElementById("mydiv").style.color="#ff0000";

add element in certain place

When I use document.createElement javascript will add an element at bottom of body.
How can I add an element in certain place ? (with document.createElement property, I mean store in a new variable)
<html>
<head>
</head>
<script type="text/javascript">
var my_div = null;
var newDiv = null;
function addElement()
{
newDiv = document.createElement("div");
newContent = document.createTextNode("test");
newDiv.appendChild(newContent);
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}
</script>
<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>
When I use document.createElement javascript will add an element at
bottom of body.
No, an element is returned, but it is not attached to anything. You need to do that yourself:
var ptag = document.createElement('p');
ptag.innerHTML = "hello world";
var someplace = document.getElementById('some_element_id');
someplace.appendChild(ptag);
That's plain js; the jquery techniques are terser.
You can add dom/Element at the start or at the end of any DOM element using jquery.
See the below example
​
<!-- HTML CODE -->
<div id="item">
this is only test
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
JQUERY Script:
$(document).ready(function(){
var item = "<span>New item</span>"
/* PrependTo */
$(item).prependTo('#item');
/* AppendTo */
$(item).appendTo('#item');
});
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
see the jquery documentation here and here
Just add the element as a child of another one.
For instance:
HTML
<body>
<div id="container"></div>
...
[page content here]
...
</body>
JS
newdiv = $("<div>something</div>");
$("#container").append(newdiv);
See the documentation of append
uhm, I could be wrong, but if your using jQuery, are you looking for something like:
var newDiv = $("<div />");
Also if you have a jQuery list of elements (an object array) like $(".divs") which procs as [[Object Object], [Object Object]] (whereas each [Object Object] is a div element containing class .divs) you can add a new element to that list (without pasting to html body till ur rdy) by doing
$(".divs").add(newDiv);

JavaScript Getting ID of A Div

I have a div box with its id and an textarea.
When I click on my div box I should get div ID through Javascript and get it printed on the textarea. I have tried but its not working. when I click the text area it says "undefined". Kindly help me.
Here is the code:
<html>
<head>
<script type="text/javascript">
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls.id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id()" style='border-width:1px;border-color:#C0C0C0;border-style: solid;background-color:#C0C0C0;width:130px;height:10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>
getElementsByTagName returns a nodeList of DOM nodes, which acts like an array.
You'll need to select the first item in the node list before you can access the node's ID:
textEl.value = divEls[0].id;
Alternatively, you could have passed this to get_id():
function get_id(node) {
var textEl = document.getElementById('mytextarea');
textEl.value = node.id;
}
onclick="get_id(this)"
But honestly, all of the JavaScript should be external to your HTML file. HTML belongs in .html files, CSS belongs in .css files and JS belongs in .js files.
//i haven't checked this code, and you probably want to modify it to be more generic.
window.onload = function () {
var myDiv, myTextArea;
myDiv = document.getElementById('mydiv');
myTextArea = document.getElementById('mytextarea');
myDiv.onclick = function () {
myTextArea.value = myDiv.id;
};
};
Rewrite your code as below:
<html>
<head>
<script type="text/javascript">
function get_id(element) {
var textEl = document.getElementById("mytextarea");
textEl.value = element.id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id(this)" style='border-width: 1px; border-color: #C0C0C0;
border-style: solid; background-color: #C0C0C0; width: 130px; height: 10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>
When you use getElementsByTagName, you get ALL of the elements with that tag as an array.
If you want the first DIV then you need to add [0] this way:
var divEls = document.getElementsByTagName("div")[0];
The remaining code is ok.
getElementsByTagName returns an array even if it contains only one object. You should access it like this:
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls[0].id;
}
divels is, as the plural is indicating, an Array (correct: a NodeList), which has no id property. Its items have, so eg. textEl.value=divEls[0].id; will work (if the List is empty, this will throw an error).
try this function
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls.item(0).id;
}
Ok I figured it out. document.getElementsByTagName("div") will return all the elements which have tag name div as an array of nodes. Here in your code there is only one div element hence first element is div itself. As in an array first element has number index = 0 so we can get first by document.getElementsByTagName("div")[0] or in your code divEls[0], and then we can get its id by simply getting divEls[0].id. Now as we have got the div id we can set the value of text area equal to this div id as: textEl.value = divEls[0].id Here is your code with changes. Hope this Helps
<html>
<head>
<script type="text/javascript">
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
/*get the first item in the nodelist ie divEls[0] = document.getElementsByTagName("div")[0] and then get its id by
its id by divEls[0] */
textEl.value = divEls[0].id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id()" style='border-width:1px;border-color:#C0C0C0;border-style: solid;background-color:#C0C0C0;width:130px;height:10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>

Categories

Resources