Can't insert a div into another internal div - javascript

I need your help to solve a problem I have.
I have this code:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="aaa()"/>
</div>
</div>
I want to use insert into the internal div (id=edit1) another new div I generated.
I tried alike code but it's not running:
js:
function aaa()
{
var elem = createDivLine();
var el1 = document.getElementById("div1");
var el2 = el1.getElementById("edit1");
el2.appendChild(elem);
}
function createDivLine()
{
var tempDiv1 = document.createElement("div");
tempDiv1.innerHTML = "Sam";
return tempDiv1;
}
The result should looks like this:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="createDivTable()"/>
<div>"Sam"</div>
</div>
</div>
JSFiddle: http://jsfiddle.net/KknXF/

Since IDs are unique, it is not valid to attempt to get an element's children by ID.
Remove this line:
var el1 = document.getElementById('div1');
And change the following line to:
var el2 = document.getElementById('edit1');
In the event that you have some irrepairably (I can never spell that word...) broken HTML that you can't possibly change, try this:
var el2 = document.querySelector("#div1 #edit1");

It should be
function aaa() {
var elem = createDivLine();
var el2 = document.getElementById("edit1");
el2.appendChild(elem);
}
Demo: Fiddle

Related

Deleting the last Element in a Div [JavaScript]

I'm having a strange problem. I'm trying to make a program that will add and delete div's inside another div called "body". To add divs, I use document.getElementById("body").innerHTML. Adding works fine. However, in the deleting function, I replace the "body" id with a variable with the id of the div that will be deleted. But when I run the code, I get the error "cannot set innerHTML of null". I tried to replace the id variable with a fixed local variable, and it worked fine. I also tried to add quotes to the variable but that didn't work either. Is there any reason why I can't set the id to a changing variable? Thanks.
Here is my code:
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '" + i + "'><br><textarea id = '1' > foo < /textarea></div > ";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i);
deleteDiv.innerHTML = "";
i--;
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
you are incrementing i after adding a div so you must use i-1 while deleting to get correct id.
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '"+i+"'><br><textarea id = '1'>foo</textarea></div>";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i-1);
deleteDiv.remove();
i--;
}
<div id = "body2">
<div id = "0">
<textarea id = "text">lol</textarea><button onclick =
"myFunction()">Add</button>
<button onclick = "myFunction2()">Delete</button>
</div>
</div>
To remove last child, you can even use CSS selector last-child. You should also add specific class to newly added divs as you would want to remove only newly added divs.
This will also remove dependency of i.
As an addon, you can also use document.createElement + Node.appendChild instead of setting innerHTML. .innerHTMl will be expensive for highly nested structure.
function myFunction() {
document.getElementById("body2").appendChild(getDiv());
}
function getDiv(i){
var div = document.createElement('div');
div.classList.add('inner')
var ta = document.createElement('textarea');
ta.textContent = 'foo';
div.appendChild(ta);
return div;
}
function myFunction2() {
var div = document.querySelector('#body2 div.inner:last-child')
div && div.remove()
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
You can refer "innerHTML += ..." vs "appendChild(txtNode)" for more information.

JavaScript function to hide buttons if specific text shows

I have a function called hideButtons that i want to hide buttons if certain text is present in the paragraph.
The paragraph goes through a list of names that the user either likes or dislikes and then when there are no more names then the buttons disappear.
Obviously this is sudo at the moment:
function hideButtons(){
if namespace.indexOf("Out of people"){
#likeButton = hidden;
#dislikeButton = hidden;
}
}
This is a working function
function showName(){
var name = names[0];
if (!name){
name = 'Out of people';
}
console.log(names)
document.getElementById('namespace').innerHTML = name;
}
And the html:
<body>
<p id='namespace'> Namelist </p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>
You are sort of mixing up javascript and jQuery.
In javascript, to get the value of a p tag:
var ns = document.getElementById('namespace').innerHTML;
the same thing in jQuery:
var ns = $('#namespace').text();
jQuery uses the CSS selectors to identify elements, javascript does not.
Here is a semi-working version of your code.
var lb = document.getElementById('likebutton');
lb.addEventListener('click', hideButtons, false);
var db = document.getElementById('dislikebutton');
db.addEventListener('click', hideButtons, false);
function hideButtons(){
var ns = document.getElementById('namespace').innerHTML;
alert(ns);
if (ns.indexOf("Namelist") > -1 ){
lb.style.display = 'none';
db.style.display = 'none';
}
}
function showName(){
var name = names[0];
if (!name){
name = 'Out of people';
}
console.log(names)
document.getElementById('namespace').innerHTML = name;
}
<body>
<p id='namespace'>Namelist</p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>
Here is the same code in jQuery:
$('#likebutton, #dislikebutton').click(function(){
var ns = $('#namespace').text();
if ( ns.indexOf('Namelist') > -1 ){
$('#likebutton').hide();
$('#dislikebutton').hide();
}else{
alert('P tag does not contain the word namespace');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<p id='namespace'>Namelist</p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>

javascript copy div change innerHTML id

I need to copy content from one div to another one with changing button's id (increment them)
Sample:
<script type="text/javascript">
function add(){
document.getElementById('two').innerHTML = document.getElementById('one').innerHTML;
}
</script>
<div id="one">
<button id="button_1" >Button_1</button>
</div>
<div id="two"></div>
<button onclick="add();">Add</button>
This of course can't work properly.
Result should be following:
<div id="two">
<button id="button_2" >Button_2</button>
</div>
Any simple way how to do this ?
If you want copy the button onclick of a button it will work for you i guess..
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('one');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "one" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
<div id="one">
<button id="button_1" >Button_1</button>
</div>
<button id="button" style="color:red">Add</button>
I've made small change in 'id' of the wrapping div.
<div id="1" class="button">
<button id="button_1" >Button_1</button>
</div>
<button onclick="add();">Add</button>
<script type="text/javascript">
function add(){
var count = document.querySelectorAll('.button').length;
var newCount = count+1;
var elDiv = document.createElement('div');
elDiv.setAttribute("id", newCount);
elDiv.setAttribute("class", "button");
elDiv.innerHTML = '<button id="button_"+newCount+">Button_'+newCount+"</button>";
document.getElementById(count).appendChild(elDiv);
}
</script>
However it can be done in more simpler way using jQuery. Hope this helps.
Are you looking for something like this. With a good mastery of jQuery traversal you may not even need to give each button an id. May be a common class may serve you well.
$(function() {
var last = $('.container');
var curr = last;
$('#add').on('click', function() {
last = curr.clone();
last.find('button').attr('id', function() {
return 'button_' + ( $('div.container').length + 1 );
})
.html(function() {
return 'Button_' + ( $('div.container').length + 1 );
}).end()
.insertAfter( curr );
curr = last;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button id="button_1" >Button_1</button>
</div>
<button id="add">Add</button>
Using JQuery:
function add( fromId, toId ){
content = $('#'+fromId).clone();
button = content.find('button');
if( button.length == 1 ){
buttonId = button.attr('id');
number = buttonId.match(/\d+/g);
number = parseInt(number[0]) + 1;
button.attr('id','button_' + number);
button.html('Button_' + number);
}
$('#'+toId).html(content.html());
}
Just call
add('one','two');

How to print array in order have same class name div

How to print array in order have same class name div. i try this code but it was print the same value of the last array. have any other way to do this
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
for(var i=0;i<sub_count;i++)
{
$(".block").attr(data-id,full_sub[i]);
$(".block").html(full_sub[i]);
}
});
</script>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>
Try
$(".block").each(function(index)
{
$(this).attr("data-id",full_sub[index]);
$(this).html(full_sub[index]);
});
In your code, each time you are assigning the html() to whole elements with the class .block. Here the html() is assigned to each tags with the same class name.
Also you forgot to put data-id in "". Otherwise it will take it as a variable, which causes the error..
Your current code overwrites all of the elements with the class of block in each loop iteration. Instead, create a parent element and append elements:
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
var parent = document.querySelector('#parent');
for(var i=0;i<sub_count;i++)
{
var div = document.createElement('div');
div['data-id'] = full_sub[i];
div.textContent = full_sub[i];
parent.appendChild(div);
}
});
</script>
<div id="parent"></div>
Working JSFiddle
If you do that way it will always print the same value of the last array.
You should use JQuery append function to append block div into a wrap div.
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
for(var i=0;i<sub_count;i++)
{
$("#wrapBlock").append('<div class="block" data-id="'+ full_sub[i] +'">'+ full_sub[i] +'</div>');
}
});
</script>
<div id="wrapBlock"></div>
That's my solution, hopefully it's helpful!
Try this.
HTML
<div class="block" ></div>
<div class="block" ></div>
<div class="block" ></div>
<div class="block" ></div>
Script
var sss = '5#45#41#25#65',
full = sss.split('#'),
full_sub = full[1].split('#');
$('.block').each(function(index){
$(this).attr('data-id', full_sub[index]);
$(this).html(index+1);
});
Fiddle Demo
The problem is that when you call $(".block").html(full_sub[i]);, you are setting it on all the divs with class .block; By doing the loop, you overwrite them each time and once you get out of the loop, they are set to the last value
Anoop's code works, an alternative is
var blocks = $(".block");
for(var i=0;i<sub_count;i++)
{
$(blocks[i]).attr('data-id',full_sub[i]);
$(blocks[i]).html(full_sub[i]);
}
The trick is that you can get at each of the items in jQuery's collection by using obj[intIndex] so that you're not dealing with all of them.
The each method is the jQuery way of doing it, it will iterate through each of the elements in the jQuery object, passing it the index, and this will point to the element being iterated
$(".block").each(function(index) {
$(this).attr("data-id",full_sub[index]);
$(this).html(full_sub[index]);
});

Remove existing code side of div code

Goal:
If there are any html syntax code or data inside of
<div id="feedEntries"></div>
Then everything should be removed and be contained empty only.
Problem:
What syntax do I need in order to remove every code and data inside of
<div id="feedEntries"></div>
Please remember that i don't want to add any class or id inside of "feedEntries"
<h3>Search</h3>
<div class="content">
<form>
<input type="text" width="15" value="searchword" id="searchTermTextField"><input type="button" name="some_name" value="Sök" id="searchButton">
</form>
<div id="feedEntries">
</div>
</div>
function fetchSearchResults(json) {
var feedEntriesDivElement = document.getElementById('feedEntries');
var ulElement = document.createElement('ul');
if (feedEntriesDivElement.children.length >= 0)
{
// Syntax code to remove the code/data
}
for (var i = 0; i < json.responseData.results.length; i++)
{
var liElement = document.createElement('li');
var personText = document.createTextNode(json.responseData.results[i].titleNoFormatting);
var newlink = document.createElement('a');
newlink.setAttribute('href', json.responseData.results[i].url );
newlink.appendChild(personText);
liElement.appendChild(newlink);
ulElement.appendChild(liElement);
}
feedEntriesDivElement.appendChild(ulElement);
}
Using pure DOM and Javascript (sometimes considered better than altering innerHTML):
if ( feedEntriesDivElement.hasChildNodes() )
{
while ( feedEntriesDivElement.childNodes.length >= 1 )
{
feedEntriesDivElement.removeChild( feedEntriesDivElement.firstChild );
}
}
feedEntriesDivElement.innerHTML = ''; should do the trick.
you can use jquery like this $('#feedEntries').empty()
to remove from javascript please check the post
document.getElementByIf('feedEntries').innerHTML = ''

Categories