Hello i am trying to dynamically create divs, at a button click, and append a span element to it. When i click the button a function is called and a div is created but i can't display the contents of the span element.
I basically have a container div and want to create divs inside that container, with the contents of the span element present, through javascript.
function createDiv ()
{
var boxEle = document.createElement('div');
var container = document.querySelector('.container');
boxEle.setAttribute('id','box_id'+ dynamicid());
//console.log(boxEle.id);
boxEle.style.width = "40%";
boxEle.style.height = "500px";
boxEle.style.backgroundColor = 'yellow';
boxEle.style.margin = "20px";
boxEle.style.boxsizing = "border-box";
boxEle.innerHTML = '<span class="list-names"></span>';
container.appendChild(boxEle);
}
This span will show a list of names that were fetched from a database. The idea was to create how many divs i wanted with the list present in every created div.
If i change the span element and insert some random text it works fine. I also tried to create a php file with just the span element there and used jquery load to insert it into my div but it only works on the first div, if i create more than one then nothing shows on the rest.
After looking on here i tried to do everything with jquery but the problem was the same.
$(function(){
var count = 0;
$('#creatediv_id').click(function(){
$('#container_id').append('<div id="first'+count+'"><span class="list-names"></span></div>');
count++;
});
});
Don't really know what else i should try or if it is doomed.
Actually your code works just fine, did you check DOM after click, because elements are there, but your span hasn't got any text, so there is nothing on the screen, here is example with jQuery way:
$(function(){
var count = 0;
$('#creatediv_id').click(function(){
$('#container_id').append('<div id="first'+count+'"><span class="list-names">test</span></div>');
count++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="creatediv_id">Create Div</button>
<div id="container_id"></div>
Related
At the moment I am using the following code which on the click of an HTML div element, changes the inner text to "Hello World":
<div id = "one" onclick = "click('one')" >text</div>
<script>
function click(id){
document.getElementById(id).innerHTML = "Hello World";
}
</script>
This works as expected and changes the content of the div to "Hello World".
The problem I am facing is at the moment I am using the id as a parameter input for the function and so that also means that for each div element that I create I would have to manually write its id within the onclick function.
I am able to create div elements using the following script which takes a value from an HTML input box, turns into a number then uses that number in a for loop to create as many div elements as specified:
<script>
function numberOfDivs(){
var divValue = parseInt(document.getElementById("inputbox").value, 10);
for(var i = 1; i < divValue + 1; i++){
var newDiv = document.createElement("div");
var divText = document.createTextNode("text")
//newDiv.setAttribute("onclick", "click()");
newDiv.appendChild(divText);
var whatIAmAppendingTo = document.getElementById("one");
whatIAmAppendingTo.appendChild(newDiv);
}
</script>
Now the problem that I having is applying that click() function to any of the new div elements that have just been created so that the click() function only affects the div that I have clicked on. I have included the setAttribute line when I create the new div elements so there is no problem linking it to the click() function.
I believe that there are two options:
-Either create new code within the numberOfDivs() function and use the var i to create an id that would be different for each new div element that I create, since var i increases to a different value each time the for loop repeats.
or
-Rewrite the click() function so that instead of having to use an id paramater I can instead make the function applicable to all div's. I was roughly thinking along the lines of using the 'this' keyword within that code, or anything along those lines so that it applies to only the div element that I click on.
With both of these possible solutions I'm not quite sure how to execute them so it would be great help if someone would be able to give me an example how it works.
Any questions or clarifications feel free to ask.
The problem I am facing is at the moment I am having to use the id as a parameter input for the function ...
No, you don't; you can pass this into your function, which is a reference to the div the click occurred on:
<div id = "one" onclick = click(this) >text</div>
Then in your function, use that argument rather than document.getElementById(id):
function click(div){
div.innerHTML = "Hello World";
}
Now you can use the same function for multiple divs.
Note, though, that if you're creating the divs programmatically, there's a better answer than setting the onclick attribute: addEventListener (attachEvent on older versions of IE). In your function creating divs:
var newDiv = document.createElement("div");
var divText = document.createTextNode("text")
if (newDiv.addEventListener) {
newDiv.addEventListener("click", click, false);
}
else {
newDiv.attachEvent("onclick", click);
}
Within click, use this:
function click(){
this.innerHTML = "Hello World";
}
typo in innerHTML and onClick
text
<script>
function click(id){
document.getElementById(id).innerHTML = "Hello World";
}
</script>
and
<div id = "one" onClick ="click('one')" >text</div>
Could this idea be helpful? Create your divs as (example for id='one'):
<div class='mydivs' id='one' ></div>
And then, detect the click on the div using a class and one event handler using JQuery:
$(".mydivs").click( function() {
id = $(this).attr('id');
click(id);
});
<div id="one">
<!-- dynamically added child nodes -->
</div>
<script>
$.ready(function(){
$('#one').children().livequery('click', function(event){
this.innerHTML = "Hello world";
});
});
<script>
Here we can use livequery to add click handlers to child elements that will be added dynamically.
if you provide your newly created divs with a common class e.g. clickable you could do this
$function(){
//Any click event of the body element that originates from a ".clickable"
//will be handled by the provided handler
$("body").on("click",".clickable",function(){
$(this).html("Hello world");
});
//... anything else that has to happen on document ready
});
I am making a simple web app. In one part of it, I have a dynamically generated list:
which is achieved with:
for(var i=0; i<goalsObj.length; i++){
var node = document.createElement("li");
node.setAttribute("class", "list");
node.setAttribute('id','g'+i);
var checkbox = document.createElement("input");
checkbox.setAttribute("type","checkbox");
checkbox.setAttribute("class", "tickbox");
node.appendChild(checkbox);
var textnode = document.createTextNode(goalsObj[i]);
node.appendChild(textnode);
document.getElementById("sortable").appendChild(node);
}
And I have a jQuery function executed when any item on the list is clicked, to app a Calendar below it.
which is achieved with:
var cal = document.createElement("p");
cal.innerHTML=calendar_html;
document.getElementById($(this).attr('id')).appendChild(cal);
Anyhow, I am getting a very shabby output:
What's wrong? What should I do? How do I make the pre-existing elements(all made dynamically) to make way for the newly created ones?
Generate the whole content at once and not in parts. Hide the content that you do not want on initialization of the page. Write a function to show the hidden content when the list items are clicked.
Paragraph ("p" element) is for organization of information into paragraphs.
http://www.w3.org/TR/html401/struct/text.html#h-9.3
I suppose you should try to use div instead of p
var cal = document.createElement("div");
cal.innerHTML=calendar_html;
Ok, if you go here: http://devs.dream-portal.net/smf205/index.php?action=forum
You will notice a table element that contains (under the menu) a forum (board index) on the right and 2 blocks of content on the left. All of this is within a table element with the class dp_main on the table element. On the right is SMF content and here's where it gets tricky. Ok, this td element has an id of smf_col I need to take out ALL HTML from within the #smf_col td element and place it just before (or in the same spot in the DOM) the table element is. Than I need to remove the table element .dp_main altogether from the DOM (and all of it's contents), than place all contents from within the body tag into the EMPTY #smf_col td element of the table, and than put that table into the body tag.
I can only do this in the body tag, so that's why the table needs to be removed from the DOM and placed back into it once the entire body contents gets placed into the td element with id = smf_col.
Using the following jQuery (a lot of manipulating here, because I can only do this in the body tag):
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
var $smf_content = $("#smf_col").contents();
$("#smf_col").empty();
$($smf_content).insertBefore($(".dp_main"));
var $dptable = $(".dp_main").contents();
$(".dp_main").remove();
var $body = $("body").contents();
$("body").empty();
$("body").html($dptable);
$("#smf_col").html($body);
});
</script>
The page is here: http://devs.dream-portal.net/smf205/index.php?action=forum
I will disable my code for now, since it doesn't work anyways, and leave it in it's original state so you can see exactly what I am talking about, before manipulating anything, this is what I have to work with. Basically, this this is done properly, the 2 blocks on the left should be ALL the way to the left and the rest of the page should be on the right.
Final Result should look something like the image below:
Try
var $dpmain = jQuery('.dp_main');
var $body = jQuery('body');
var $col = jQuery('#smf_col');
var $ct = jQuery('<div />').insertBefore($dpmain);
$body.append($dpmain);
$col.contents().appendTo($ct);
$body.contents().not($dpmain).appendTo($col)
I want to swap the content of two td's with each other by clicking on move up button.
I mean I want to swap content between the 2nd td and 3rd td.
I got that done but I am facing little problem in that i.e. "the swapped td's are not toggling the class that shows the current td is clicked or not after the swapping."
I am using this code for swapping the content of td's as below
var currentTr = $("#selectedTab td.backgroundcolor").parent();
var previousTr = currentTr.prev();
var temp = currentTr.html();
$(currentTr).html(previousTr.html());
$(previousTr).html(temp);
HTML manipulation in the DOM can be destructive. You should instead move the DOM nodes themselves.
var currentTr = $("#selectedTab td.backgroundcolor").parent();
var previousTr = currentTr.prev();
var temp = currentTr.contents().detach();
currentTr.append(previousTr.contents());
previousTr.append(temp);
This way you're not serializing, destroying and rebuilding all the nodes. You're just moving them.
Hi I'm working on a site. I need help making a text appear in a div where it saids any image clicked their title and size. in DOM scripting. Can anyone help? No innerhtml.
Thanks
using pure dom scripting and no helper framework like jquery, gotta dust off some things I haven't used in awhile!
That said here ya go. Must be placed after page has loaded. (Or remove the last "showCredit();" line and put it in your body onload.
Note you'll need to alter this, I just put the "source" in the text, other attributes and styling is up to you.
function showCredit(){
//find all image tags we want
var elements = document.getElementsByTagName('img')
//iterate through them
for(var i=0; i<elements.length;i++){
//bind the onclick function to all image tags
elements[i].onclick=function(){
//create the new div
var el = document.createElement('div')
//alter this to be whatever text you want
var text = document.createTextNode('Source = '+this.getAttribute('src'));
//alter this if you're going to have more than one clickable div
el.id = 'test';
//add the text to the div
el.appendChild(text);
//add the new div after the image tag
this.parentNode.insertBefore(el, this.nextSibling);
//set a timer to find the element we've named "test" and remove it
window.setTimeout(function(){
var element = document.getElementById('test');
if(element){
element.parentNode.removeChild(element);
}
}, 4000);
}
}
}
//execute the function (bind all images)
showCredit();