Change innerhtml of all h2 elements within div - javascript

This is probably a stupid mistake, but i can't seem to get this to work.
I'm trying to change the innerhtml of all the H2 elements withing the div whose id=variable id.
var numberOfQuestions = $('.question').length;
var id = "question"+(numberOfQuestions);
clone.id=id;
document.documentElement.getElementById(id).getElementsByTagName( "h2" ).innerhtml= "Question"+(numberOfQuestions);
I think I'm doing something wrong here: document.documentElement.getElementById(id).getElementsByTagName( "h2" ).innerhtml= "Question"+(numberOfQuestions);
The nrtire script:
<script type="text/javascript">
function copyAppendRow() {
var question = document.getElementById("question");
var clone=question.cloneNode(true);
var numberOfQuestions = $('.question').length;
var id = "question"+(numberOfQuestions);
clone.id=id;
var questiondiv = document.getElementById(id);
var h2s = questiondiv.getElementsByTagName("h2");
for(var h = 0; h < h2s.length; h++ ) {
h2s[h].innerHTML = "Question"+(numberOfQuestions); }
if($('#questionsuccess').css('display') == 'none'){
$('#questionsuccess').fadeIn('fast');
$('#questionsuccess').fadeOut(4000);
}
}
</script>

do you mean something like:
var divEle = document.getElementById("yourDivId");
var h2s = divEle.getElementsByTagName("h2");
for(var h = 0; h < h2s.length; h++ ) {
h2s[h].innerHTML = "Question"+(numberOfQuestions);
}
OR
jQuery way:
$("#"+yourDivId + " > h2").html("Question"+(numberOfQuestions));

I see from your first line that you are already using jQuery, so make life easy for yourself and use it to do this task.
$('#' + id + ' h2').html( 'Question ' + numberOfQuestions );
The jQuery selectors work just like CSS selectors. So this line of code finds the element with your variable id as its' id and gets all the h2 tags within that element. .html is a jQuery method that sets the inner HTML of an element.

Related

Generate HTML with JavaScript not working?

I'm quite new to JavaScript so I don't understand what's not working.
The Code:
var postCount = 0;
function generatePost(title, time, text) {
var div = document.createElement("div");
div.className = "content";
div.id = "post_" + postCount;
document.getElementById("postcontainer").appendChild(div);
var h3 = document.createElement("h3");
div.id = "post_h3_" + postCount;
h3.innerHTML = title;
document.getElementById("post_" + postCount).appendChild(div);
var span = document.createElement("span");
document.getElementById("post_h3_" + postCount).appendChild(div);
span.innerHTML = time;
var paragraphs[] = text.split("||");
for (var p : paragraphs[] {
var paragraphCount = 0;
var h3 = document.createElement("h3");
document.getElementById("post_p_" + postCount + "_" + paragraphCount).appendChild(div);
paragraphCount++;
}
postCount++;
}
function loadPosts() {
generatePost("Testing Title", "I don't know", "This is || a paragraph");
}
I included it with:
<body onload="loadPosts()">
In the end, nothing shows up. Not even in the Inspector in my Browser. Is my Code even run? Did I forget an essential doStuffNow()?
Second: If I add a class to a div with JavaScript, do the CSS-Rules in the style.css append to it?
To answer the second part of your question, yes, the CSS styling that applies to a class will be added to an object that you add the same class to.
You have errors in your code. What editor do you use? You can also use browser console to check for errors in your page.
Check here:
var paragraphs = text.split("||");
for (var p in paragraphs) {
/*
*
* Where do you use your var p?
*
*/
var paragraphCount = 0;
var h3 = document.createElement("h3");
document.getElementById("post_p_" + postCount + "_" + paragraphCount).appendChild(div);
paragraphCount++;
}
Why don't you try with jQuery?

Div's are being generated dynamically and even the (obj.search) fetches the data but nothing is being displayed in it. How do i display the data?

JS doesn't display the output
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.id = "div"+i;
divTag.className = "list";
document.getElementById('div'+i).innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
}
Image here
You missed adding the newly created element to the DOM. Example:
document.getElementById("yourDivContainer").appendChild(divTag);
Fiddle:
http://jsfiddle.net/mbpfgm49/
You need to append your div tags to some element (e.g: body), to make text appear on page
// Let's create some sample data
var obj = {
Search: []
}
var currentYear = (new Date).getFullYear();
for (var i = currentYear - 10; i <= currentYear; i++) {
obj.Search.push({
Title: 'Test',
Year: i
})
}
// Here goes your code fixed
for (var i = 0; i < obj.Search.length; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.className = "list";
divTag.innerHTML = obj.Search[i].Title + ' ' + obj.Search[i].Year;
document.body.appendChild(divTag);
}
Yes, you have to add the element to the DOM.
More basically, it is an anti-pattern to construct IDs for elements and use those as the primary means for referring to elements, by means of calling getElementById at every turn. I guess this approach is one of the many lingering after-effects of the jQuery epidemic.
Instead, keep references to elements directly in JS where possible, and use them directly:
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.className = "list";
parent.appendChild(divTag);
^^^^^^^^^^^^^^^^^^^^^^^^^^ INSERT ELEMENT
divTag.innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
^^^^^^ REFER TO ELEMENT DIRECTLY
}
To be absolutely pedantically correct, what you are creating is not a "tag", it's an "element". The element is the DOM object. The "tag" is the div which characterizes the element type.

JS: split and replace 1 ul into 2 equal ul's

I have a variable in which i search for ul's. I want every ul to split into 2 equal ul's and replace the original ul with these 2 new ul's.
I can't do this with CSS, because i want the li's to display from top to bottom every column, instead of from left to right.
I have the following code, but I am stuck right now...
<script type="text/javascript">
var wid_tekst1 = "<?php echo $wid_tekst1; ?>";
$(wid_tekst1).filter('ul').each(function() {
//Create array of all posts in lists
var postsArr = new Array();
$postsList = $(this);
$(this).find('li').each(function(){
postsArr.push($(this).html());
})
//Split the array at this point. The original array is altered.
var firstList = postsArr.splice(0, Math.round(postsArr.length / 2)),
secondList = postsArr,
ListHTML = '';
function createHTML(list){
ListHTML = '';
for (var i = 0; i < list.length; i++) {
ListHTML += '<li>' + list[i] + '</li>'
};
}
//$(firstList).before('<ul>');
//$(firstList).after('</ul>');
//$(secondList).before('<ul>');
//$(secondList).after('</ul>');
alert(firstList);
alert(secondList);
})
</script>
Thanks for your help...
UPDATE:
I now have the following:
<script type="text/javascript">
$( document ).ready(function() {
var wid_tekst1 = $('.content');
$(wid_tekst1).filter('ul').each(function() {
var $li = $(this).children(),
$newUl = $('<ul>').insertAfter(this),
middle = Math.ceil($li.length / 2) - 1;
$li.filter(':gt(' + middle + ')').appendTo($newUl);
//alert($newUl);
});
});
</script>
It doesn't split the ul's into 2. The only way I got it working was by setting
var wid_tekst1 = "*";
But if I set variable wid_tekst1 to all, it replaces all ul's in the webpage. I only want to replace the ul's within the .content-class
Thank you
Your code can be optimized:
$(wid_tekst1).filter('ul').each(function() {
var $li = $(this).children(),
$newUl = $('<ul>').insertAfter(this),
middle = Math.ceil($li.length / 2) - 1;
$li.filter(':gt(' + middle + ')').appendTo($newUl);
});
Demo: http://jsfiddle.net/R3VYZ/
Messing with innerHTML (when you construct lists using strings) is not ideal, since you will lose all event original handlers if there were something bound.

Adding new nested div to document

I want to add a div with a child div to the document but append() seems to be the wrong option for this, what should I use instead?
//Create Statusbar
var status = $('#status');
for (var i = 0; i < resources.length; i++) {
var resource = document.createElement('div');
var resourceCounter = document.createElement('div');
resourceCounter.id = "r" + (i + 1);
//resource.className = "resource";
resource.innerHTML = resources[i];
resourceCounter.innerHTML = saveData.resources ? saveData.resources[i] : 0;
resource.style.background = "url('images/resources/" + resource.id + ".jpg') 0 26px / 100% auto no-repeat";
resource.onclick = function () {
alert(this.id);
};
resource.append(resourceCounter);
status.append(resource);
}
resource.append(resourceCounter); --> Uncaught TypeError: Object #HTMLDivElement has no method 'append'
here resource is a dom element, append is a method provided by jQuery, it is not present in the dom element
you can use appendChild instead
resource.appendChild(resourceCounter);
or wrap resouces with jQuery and use append
$(resource).append(resourceCounter);

javascript appenchild

for(var i=0; i<myJSONObject.model.length; i++){
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
create_div.innerHTML = myJSONObject.model[i].model_name;
var assign_innerHTML = create_div.innerHTML;
var create_anchor = document.createElement('a');
document.getElementById('models').appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
}
for ex the myJSONObject.model.length is 2
the output is like this
<div id = 'model_id0'>XXXXX<a> </a></div>
<div id = 'model_id1'>XXXXX<a> </a></div> */
but instead of above the output sholud be like this
<div id = model_id0> <a> xxxxxx</a></div>
<div id = model_id1> <a> xxxxxx</a></div>
how to append it inside of the innerhtml
any one plz reply !!!!
two suggestions:
1.) instead of assigning innerHTML to model_idx div assign the model name to its child a. and 2nd instead of appending it to DOM in every loop do it after completing the loop as to minimize frequent the DOM Update ie by:
objContainer = document.createElement('div');
for(....)
{
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
var create_anchor = document.createElement('a');
create_anchor.innerHTML = myJSONObject.model[i].model_name;
create_div.appendChild(create_anchor);
objContainer.appendChild(create_div);
}
document.getElementById('models').appendChild(objContainer);
I would go along the lines of:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
create_div.id = "model_id" + i;
create_div.innerHTML = "<a>" + model.model_name + "</a>";
models.appendChild(create_div);
}
Unless you specifically need to do something to the anchor itself (other than set its innerHTML), there's no need to create a reference to an element for it. If you do need to do something specific to that anchor, then in that case have this, instead:
EDIT: As per your comment, you DO want to do something to the anchor, so go with this (now updated) option - assuming the anchor will always be a child of the div that has the ID you require. The reason "model_id" + i is being put in as a string is because that is exactly what is being passed into the HTML - the document has no clue what "i" is outside of javascript:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
var create_anchor = document.createElement("a");
create_div.id = "model_id" + i;
create_anchor.innerHTML = model.model_name;
if(window.addEventListener) {
create_anchor.addEventListener("click", function() {
getModelData(1, this.parentNode.id);
}, false);
} else {
create_anchor.attachEvent("onclick", function() {
getModelData(1, this.parentNode.id);
});
}
create_div.appendChild(create_anchor);
models.appendChild(create_div);
}

Categories