How to get contents of a child div javascript - javascript

I want to get the get the contents of a div that's inside another div and put them in a list, to send it to the database after that.
I loop around the div and get all it's contents but all what it just returns the content of the first item of the loop.
The Div looks like this:
$('#Classes').append('<div> <h1 class = "flip" wpID="' + subjects[i].Wkp_ID+ '</h1><div id ="NewBody" class="panel" contenteditable>' + subjects[i].Wkp_Body + '</div> </div>');
I use these lines to get the content:
$('#Classes div').each(function (index) {
var header = $(this).children('h1');
var wpID = header.attr('wpID');
var WeekBody = document.getElementById("NewBody");
var Weekbodycontent = WeekBody.innerHTML;
WeekPlan[index] = {"Wkp_Body": WeekBody};
});
So , do you know how can I add all the items to the list one by one ?
Thanks

You have several issues. First off, you can't have the same ID present in more than one object in your document. You need to change that.
Then, I would suggest this type of solution using a class on the desired .panel div:
$('#Classes').append('<div class="container"><div class="panel" contenteditable>' +
subjects[i].Wkp_Body + '</div> </div>');
$('#Classes .container').each(function (index) {
var header = $(this).children('h1');
var body = $(this).find(".panel");
var Weekbodycontent = body.html();
WeekPlan[index] = {"Wkp_Body": body.get(0)};
});

Related

How to add click to dynamically created list items in jquery and html? [duplicate]

This question already has answers here:
Click event doesn't work on dynamically generated elements [duplicate]
(20 answers)
Closed 4 years ago.
I'm getting an error when setting on click to the dynamically added html elements in jquery.
First of all i should say that i searched alot in this community but i get more confused .
here is my code :
var data = ['element1','element2','element3'] ;
var html = '' ;
for(let i = 0;i<data.length ; i++){
const element = data[i];
html += '<li id="'+element+'">'+element+'</li>' ;
}
I Want to add different click functions to every list item in this code using ids .
any suggestions will be helpfull , thanks to this great community .
Here is an example using plain JavaScript showing how you can attach such click handlers to your dynamically created elements.
First you need to create the li's using document.createElement, then you set the text content and id of your li's.
The click handler can be added by setting the onclick property or using the addEventListener method.
Once your li is set, you just have to append it to a container, here a list <ul>.
const elements = ['element1','element2','element3'];
const handlers = [
() => console.log('hello 1'),
() => console.log('hello 2'),
() => console.log('hello 3')
];
const content = document.getElementById('content');
elements.forEach((id, i) => {
const li = document.createElement('li');
li.id = id;
li.textContent = `Hello ${i}`;
li.addEventListener('click', handlers[i]);;
content.appendChild(li);
});
<ul id="content"></ul>
You can use document selector for dynamically created DOM elements.
eg: for element1
$(document).on("click","#element1",function(){
//your code snippet
});
You can attach the click event on the parent element, in this case, the <ul> element. In jQuery, the .on() function has a second selector parameter which can be the li in this case.
Within the callback function, you can use $(e.target).attr('id') to find the id of the current element being clicked. This can be used to take appropriate action based on its value.
See the code below.
var data = ['element1', 'element2', 'element3'];
var html = '';
html += '<ul id="ulElement">';
for (let i = 0; i < data.length; i++) {
const element = data[i];
html += '<li id="' + element + '">' + element + '</li>';
}
html += '</ul>';
$('#content').html(html);
$('#ulElement').on('click', 'li', function(e) {
var clickId = $(e.target).attr('id');
console.log(clickId)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content"></div>

How can I get innerhtml except one of its child Jquery

I want to print my elements so I need to get innerHtml of the whole div but I need to hide one element from printed but still found in the main page
My attempt looks like this
var printcontent = document.getElementById(el).innerHTML
+" <div class='row'><span class='glyphicon glyphicon-tasks'></span><b></b></div>"
+ document.getElementById(tble).innerHTML
+ document.getElementById(img).innerHTML;
this works fine but I need to hide the elment ID ="attach"
var panel = document.getElementById(el).innerHTML;
var filteredpanel = panel.remove(document.getElementById("attach").innerHTML)
Using jQuery:
$('#divID').not('#attach');
or
$('#divID:not(#attach)');
Try this
$('#attach').hide(); /* hide */
var printcontent = $(el).html() /* assign var */
+" <div class='row'><span class='glyphicon glyphicon-tasks'></span><b></b></div>"
+ $(tble).html()
+ $(img).html();
$('#attach').show(); /* show again */

Change existing DIV from a CLASS to an ID

Is this possible? Or is there a way to tack on and ID to an existing div?
This is my code. I can't get the code to work using classes, but I found when I used getElementById and changed the div to an ID, that it did. But I have a ton of already posted stuff so it would take forever to go through all those posts and change it manually to an ID.
Can I incorperate JQuery in this and still have it work? I tried that with something I stumbled across but it didn't work so I removed it. I don't remember what it is now though. :S
<div id="imdb" class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnum = document.getElementsByClassName("imdb");
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnum + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
window.onload = imdbdiv();
</script>
Can anyone help. I cannot for the life of me figure this out.
JsFiddle
Your problem was, you were appending the collection returned by document.getElementsByClassName instead of looping through the elements in the collection. You can verify this by looking at the href property of the link in your jsFiddle. You must loop through the values, then access the data in their innerHTML property.
You can use document.querySelectorAll to get a list of all elements matching a certain CSS selector, in your case .imdb. This is more flexible, in case you want to select elements with more than one class. I've pasted the code from the updated jsFiddle below.
function imdbdiv() {
var imdbMain = "http://www.imdb.com/title/",
end = "/#overview-top",
imdbValueDivs = document.querySelectorAll('.imdb'),
length = imdbValueDivs.length,
// Iterator values
i,
newDiv,
newLink;
// Loop over all of your link value containers
for (i = 0; i < length; i++) {
// Create the container
newDiv = document.createElement('div');
// Create the new link
newLink = document.createElement('a');
newLink.href = imdbMain + imdbValueDivs[i].innerHTML + end;
newLink.innerHTML = "My favorite film";
// Add the link to the container,
// and add the container to the body
newDiv.appendChild(newLink);
document.body.appendChild(newDiv);
}
}
window.onload = imdbdiv();
If you have many such divs on your page, then it could be like this:
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnums = document.getElementsByClassName("imdb");
for (var i =0; i < idnums.length; i++) {
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnums[i].innerText + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
}
window.onload = imdbdiv();
</script>
See jsfiddle
UPDATE:
The following string was incorrect:
window.onload = imdbdiv;
Okay, so your question is a little bit unclear.
The way I understood your question is that you have a whole bunch of div elements with class attribute and what you want is to simply copy the class value to the id attribute of the div elements.
If that's correct then try something like this with jquery:
<script>
$(document).ready(function(){
$(".imdb").each(function(imdbDiv){
var classValue = imdbDiv.attr("class");
imdbDiv.attr("id", classValue);
});
});
</script>

Creating divs with different id's

i have one question regarding creation of divs:
I have button, when user clicks on it, javascript (or jquery) needs to create a div. But when user clicks again, it should create another div, but with different id. So, every time user clicks should be created div with different id.
I partialy know how to create div, but i have no idea how to make divs with different id's.
var c = 0; // Counter
$('#add').on('click', function() {
c += 1;
$('#parent').append('<div id="child'+ c +'">'+ c +'</div>');
});
#child1{color:red;}
#child2{color:blue;}
#child3{color:orange;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">ADD</button>
<div id="parent"></div>
var divcount = 1;
$('button').click(function(){
$('<div/>', { id:'comment'+divcount++ })
});
Here's a random ID generator for you.
function createParanoidID() {
return 'id_' + Math.floor(Math.random() * 9e99).toString(36);
}
createParanoidID(); // id_1js7ogi93ixt6x29w9svozegzhal67opdt3l3cf1iqidvgazlyaeh1ha7a74bswsg
createParanoidID(); // id_1fleq6chguuyyljhy39x3g7mg661mg845oj8fphnxgvm0bdgz7t3w0q01jptogvls
createParanoidID(); // id_ajz1ft17ml4eyz08gd3thcvq3fx1ycr927i0h2zgyw8bzq9wurv1gdfogly8tbls
Using a variable as counter and the "attr" function to set the id attribute.
HTML
<button id="button">Create Div</button>
<div class="container"></div>
jQuery:
$('#button').on('click', function() {
var count = $('div.container div').length,
id = count + Math.floor(Math.random() * 100);
$('div.container').append('<div id="'+ id+'">ID of this div is: '+ id +' </div>');
});
DEMO
Here's the easy way to do this.
Firstly, you'll need a button:
​<button id="onClickOfThis​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ButtonAnewDivWithArandomIDwillBeInserted"></button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Then the javascript:
$("#onClickOfThisButtonAnewDivWithArandomIDwillBeInserted").on('click', function() {
var myID = 'randomIDnumber_'+Math.random()+Math.random()+Math.random()+Math.random()+Math.random()+Math.random();
var MyNewElement = document.createElement('div');
MyNewElement.id = myID.replace(/\./g, '');
$(MyNewElement).appendTo('body');
});
Here's a FIDDLE
If you don't want to use global counter like in previous answers you can always get number of children and use that as relative value from which you will create another id.
Something like this (with jQuery):
function add_another_div() {
var wrap_div = document.getElementById("#id_of_div_who_contain_all_childrens");
var already_childs = $("#id_of_div_who_contain_all_childrens").children().length;
var div = document.createElement('div');
var divIdName = 'new_div-'+ (already_childs+1);
div.setAttribute('id', divIdName);
wrap_div.appendChild(div);
}
Of course, this requires for all of your children to have same parent (same wrapper). If that is not the case, and they are separated across multiple wrappers, then just use unique class name for all of them, and count them like that. I found this approach much better and easier instead of using global counters which I need to take care about.

changing font size of first letter of each word with javascript append issue

I have this js that is adjusting the size of the first letter of each word in my headers. The only prob is that it appends all the results to each header. So each header on the page, becomes a combo of every header on the page. This jsfiddle link makes what Im saying much more clear:
http://jsfiddle.net/GKYuG/
Can someone please let me know how I can get the correct result?
Try this:
$(document).ready(function() {
var titles = new Array();
titles[0] = 'latest_news';
titles[1] = 'contact_me';
$('.title').each(function(){
var words = $(this).text().split(' ');
var html = '';
$.each(words, function() {
html += '<span style="font-size:200%">'+this.substring(0,1)+'</span>'+this.substring(1) + ' ';
});
$(this).html(html);
});
});
You have to iterate through the selected divs, otherwise you are applying your changes to all the divs selected by the selector.

Categories