JavaScript Getting ID of A Div - javascript

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>

Related

Create a custom element in place where the code was initialized

I'm trying to create an element using JavaScript in place where the script was initialized.
I need to be able to just call a function for the element to appear just after the <script> tag in my HTML document.
I tried this code but I don't know how to actually create an element.
function createElement() {
var container = document.createElement('div');
container.setAttribute("class", 'someDiv');
document.createElement(container);
}
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<body>
<script>
createElement("div", "someDiv");
</script>
</body>
document.currentScript seems to have good browser support, and will give us the script element containing the code currently being executed.
If what you'd like to do is replace the current script with some other element, you use it like this:
<script>
const replacementText = document.createTextNode("hi, I'm the replacement!");
document.currentScript.parentNode.replaceChild(replacementText, document.currentScript);
</script>
If you simply want to insert an element after the current script, without replacing it:
<script>
const newText = document.createTextNode("hi, I'm new text!");
const currentScript = document.currentScript;
currentScript.parentNode.insertBefore(newText, currentScript.nextSibling);
</script>
Here's a more complex example using prewritten HTML:
<script>
const currentScript = document.currentScript;
const templateFragment = (function(){
const templateEl = document.createElement("template");
templateEl.innerHTML = `
<ul>
<li>Hi!</li>
<li>I am a list!</li>
</ul>
`;
return templateEl.content;
})();
currentScript.parentNode.insertBefore(templateFragment, currentScript.nextSibling);
</script>
You could use insertBefore and target insertion point as the script like so:
var script = document.querySelector('script:last-of-type');
var container = document.createElement('div');
document.body.insertBefore.insertBefore(script, container);
Using document.currentScript, we can get a reference to the script element where the code is running and then using .nextElementSibling, we can get the next sibling node that is an element. Finally, with .insertBefore and .appendChild(), we can insert the new element just before the element passed in as an argument (the sibling that was found earlier or body if none was found).
NOTE: Don't call your function createElement as it can cause a naming conflict with document.createElement().
This will insert an element just after the script element.
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<head>
<script>
function create(type, style) {
var container = document.createElement(type);
container.classList.add(style); // Best way to add a class
container.textContent = "Hello!";
let sibling = document.currentScript.nextElementSibling;
if(sibling){
// Insert the new element before the next sibling
sibling.parentNode.insertBefore(sibling, container)
} else {
// Insert the new element at the end of the body
document.body.appendChild(container);
}
}
</script>
</head>
<body>
<p>The new element should be right below this.</p>
<script>
create("div", "someDiv");
</script>
<p>The new element should be right above this.</p>
</body>
You can use .insertBefore() to add some element before the next sibling of your script. To reference your script, you could add an id attribute to it:
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<body>
<p>I'm inside the body, before the script TAG</p>
<p>New element should appear just after this text...</p>
<script id="myScript">
function createElement()
{
var container = document.createElement('div');
container.setAttribute("class", 'someDiv');
var script = document.getElementById("myScript");
script.parentNode.insertBefore(container, script.nextSibling);
}
createElement();
</script>
<p>I'm inside the body, but after the script TAG</p>
</body>

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>');

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

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>

Javascript Function to Remove Div

I need a function that can delete the div one by one .
My code is shown below. in my code i have created a function to create a div when i click a button . and i can't figure how to delete div one by one .
Please help me with the correct code to delete div one by one.
<html>
<head>
</head>
<body>
<button id="buttonone" onclick="creatediv()">CREATE A DIV</button>
<button id="buttontwo" onlick="removedivider()">Remove DIV </button>
<script>
function creatediv()
{
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("div");
newdiv.setAttribute("id","newdiv");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
//Function to Remove the DIV one by one;
}
</script>
</body>
</html>
<script>
var index = 0;
function creatediv()
{
++index;
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("span");
newdiv.setAttribute("id","newdiv" + index);
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
document.body.removeChild(document.getElementById("newdiv" + index));
--index;
}
</script>
Should work, I didn't test.
You weren't very clear regarding which div should be removed. Also, in your code, you repeatedly appended divs with the same id. You can't do that.
I made a quick example that removes the div appended first (a queue). I gave each date an id based on the current time, but such isn't really necessary. You could always just remove the first child of the parent div to which you are appending these divs.
However, if you plan on appending these divs in places that are not necessarily all under the same parent, then giving them unique ids and storing said ids is useful.
fiddle
HTML
<button id="add">add</button>
<button id="remove">remove</button>
<div id="holder">
<p>Added divs will go here</p>
</div>
JavaScript
var ids = [];
document.getElementById("add").onclick = function () {
var id = new Date().getTime(), // generate unique id (sort of)
div = document.createElement("div"); // create a div element
ids.push(id); // push the generated id to the holder array, ids
div.appendChild(document.createTextNode(id)); // append a text node to the div
div.setAttribute("class", "newDiv"); // give it a class for styling
div.setAttribute("id", id); // set its id
document.getElementById("holder").appendChild(div); // append the div
}
document.getElementById("remove").onclick = function () {
if (ids.length) { // only perform if a div has been appended
var div = document.getElementById(ids.shift());
// ids.shift() removes and returns ids[0], or the earliest added div
// this finds that element in the DOM
div.parentNode.removeChild(div); // and removes it
} else { // otherwise alert that there are no divs to remove
alert("no divs to remove!");
}
}
CSS
.newDiv {
height: 20px;
width: 110px;
background-color: #7EA8CA;
border: solid 1px #93CC76;
}
Replace your code with the following
<!DOCTYPE html>
<html>
<head>
<title>DIVs</title>
<script type="text/javascript">
function create_div() {
document.getElementById("button1").innerHTML="CREATE ANOTHER DIV";
var div = document.createElement("DIV");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
div.appendChild(text);
div.style.color = "white";
div.style.width = "100px";
div.style.backgroundColor = "green";
document.body.appendChild(div);
}
function remove_div() {
var div = document.getElementsByTagName('DIV'), i;
for(i = div.length-1; i >= 0; i--){
div[i].parentNode.removeChild(div[i]);
return false;
}
}
</script>
</head>
<body>
<button id="button1" onclick="create_div()">CREATE DIV</button>
<button id="button2" onclick="remove_div()">REMOVE DIV</button>
</body>
</html>
By the way, you can't have multiple DIVs having the same ID. Check the working jsBin
This function assumes there will be no other div elements. It will also remove the divs in fifo order.
function removedivider() {
var divs = document.getElementsByTagName('div');
if (divs.length > 0) divs[0].remove();
}
EDIT:
Here's a jsfiddle

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);

Categories

Resources