What I'm trying to accomplish with this code is to output the array alphabet as a series of list items into an existing unordered list in the actual markup. I've got the array into list items, but I can't figure out how to tell it to append itself to an existing unordered list <ul id="itemList"></ul>.
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
document.write('<li>' + alphabet[indexNum++] + '</li>');
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
Don't use document.write to do it. You should act like this:
function write_letters(){
var letters = "";
for (var i = 0; i < alphabet.length; i++ ) {
//Also I don't understand the purpose of the indexNum variable.
//letters += "<li>" + alphabet[indexNum++] + "</li>";
letters += "<li>" + alphabet[i] + "</li>";
}
document.getElementById("itemList").innerHTML = letters;
}
More proper way is to use DOM (in case you want full control of what's coming on):
function write_letters(){
var items = document.getElementById("itemList");
for (var i = 0; i < alphabet.length; i++ ) {
var item = document.createElement("li");
item.innerHTML = alphabet[i];
items.appendChild(item);
}
}
You can use a combination of createElement() and appendChild() to add new HTML elements within another HTML element. The code below should work for you:
<html>
<head>
<title>Script Test</title>
</head>
<body>
<ul id="itemList"></ul>
</body>
<script>
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
var myElement;
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
// Create the <LI> element
myElement = document.createElement("LI");
// Add the letter between the <LI> tags
myElement.innerHTML = alphabet[indexNum++];
// Append the <LI> to the bottom of the <UL> element
unorderedList.appendChild(myElement);
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
</script>
</html>
Note how the script exists below the body tag. This is important if you want your script to work the way you wrote it. Otherwise document.getElementById('itemList') will not find the 'itemList' ID.
Try to reduce the actions on the DOM as much as possible. Every appendChild on unorderedList forces the browser to re-render the complete page. Use documentFragement for that sort of action.
var frag = document.createDocumentFragment();
for (var i = alphabet.length; i--; ) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(alphabet[indexNum++]));
frag.appendChild(li);
}
unorderedList.appendChild(frag);
So there will be only one DOM action which forces a complete redraw instead of alphabet.length redraws
Related
I want to print html code in Javascript code.
I want to open and close the bottom line of five li tags. How can I do this with a for loop
jQuery(document).ready(function () {
InsertLi();
});
function InsertLi(){
var count = 5;
for (var i = 0; i < count; i++) {
var codeBlock = ' <li>' + i + '</li>';
$(".bildirimMetin").html(codeBlock);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin">
</ul>
You need to use append function instead. html function every time overrides your html content with the new content and you get only the last one. Also create your string with 5 li-s and then call the append at the end to work with DOM one time and have more performance.
function InsertLi() {
var count = 5;
var codeBlock = '';
for (var i = 0; i < count; i++) {
codeBlock += ' <li>' + i + '</li>';
}
$(".bildirimMetin").append(codeBlock);
}
jQuery(document).ready(function () {
InsertLi();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin"></ul>
If you have only one item with bildirimMetin class, it will be better to use id instead of class.
Well, another solution, close to your code, with html, store all strings in your variable via += then you must define your variable before for loop also move your html after it. Your current code not working because it just store last string not all.
InsertLi();
function InsertLi() {
var count = 5;
var codeBlock = '';
for (var i = 0; i < count; i++) {
codeBlock += '<li>' + i + '</li>';
}
$(".bildirimMetin").html(codeBlock);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin">
</ul>
you had a couple issues. One was overwriting the inner HTML instead of appending. The other was a syntax issue.
function InsertLi(){
var count = 5;
for (var i = 0; i < count; i++) {
var codeBlock = ' <li>' + i + '</li>';
$(".bildirimMetin").append(codeBlock);
}
}
jQuery(document).ready(function () {
InsertLi();
}
);
This question already has answers here:
How can I change an element's class with JavaScript?
(33 answers)
Closed 5 years ago.
I am working on a simple example, if a user clicks on element then all the elements above it should have a class and all elements below it should not have any class applied to them.
Here is my code:
<script>
function test(object) {
var pid = object.id;
var id = parseInt(pid.split("")[1]);
console.log(id);
for (var i = 1; i <= id; i++) {
var element = document.getElementById("p"+i);
console.log(element);
element.className = "active";
}
console.log(id+1);
for(var i = id+1; i <= 4; i++) {
var element = document.getElementById("p"+i);
element.className.replace(new RegExp('(?:^|\\s)'+ 'active' + '(?:\\s|$)'), ' ');
console.log(element);
}
}
</script>
<div id="divid">
<p id="p1" onclick="test(this)">one</p>
<p id="p2" onclick="test(this)">two</p>
<p id="p3" onclick="test(this)">three</p>
<p id="p4" onclick="test(this)">four</p>
</div>
So here if I click on three then the elements for one, two, three should have the class active and element four should not have any class. This is working fine.
Now if I click on one, I am expecting that two, three, four should have any css class but it is not working like that.
Can you please help me where is the issue. I want to use plain Javascript.
It might be wise to consider an alternative to using the onclick attribute due to separation of concerns. The following allows you to alter the HTML without having to consider JavaScript while you work.
https://jsfiddle.net/gseh0wxc/2/
var getList = (selector) => [].slice.call(document.querySelectorAll(selector));
var paragraphs = getList("#divid p[id ^= 'p']");
paragraphs.forEach((paragraph, index) => {
paragraph.addEventListener('click', (e) => {
for (let i = 0; i < index; i++) {
paragraphs[i].classList.remove('active');
}
for (let i = index; i < paragraphs.length; i++) {
paragraphs[i].classList.add('active');
}
});
})
Please try this code
function test(object) {
var pid = object.id;
var id = parseInt(pid.split("")[1]);
console.log(id);
for (var i = 1; i <= id; i++) {
var element = document.getElementById("p"+i);
element.classList.add("active");
}
console.log(id+1);
for(var i = id+1; i <= 4; i++) {
var element = document.getElementById("p"+i);
element.classList.remove("active");
}
}
Hope this helps.
try this simple approach instead, don't need to extract id number and all, and with a single simple loop.
function test(option) {
//this will select all p tags id starts with "p" inside div having id "divid" and return a array
var targetPTags = document.querySelectorAll("div#divid p[id^=p]")
var idx, flag=false;
//we are iterating over that array and taking each dom element in el
for(idx=0;idx<targetPTags.length;idx++) {
var el = targetPTags[idx];
if(flag) {
//do operation you want for after elements in el
} else if(option===el) {
flag=true; // we are making flag true when its the element that clicked and doing no operation
//do the operation you want for the element, may be the same as below operation in else
} else {
//do operation you want for before element in el
}
}
}
Kind of similar to "Chatterjee"'s solution, but here you go:
function test(object)
{
var parentElem = null;
var childElems = null;
var currElemSet = false;
var i=-1;
try
{
parentElem = object.parentElement;
if(parentElem!=null)
{
childElems=parentElem.getElementsByTagName(object.nodeName); // could refine to accommodate sibling nodes only
if(childElems!=null)
{
for(i=0;i<childElems.length; i++)
{
if(currElemSet) childElems[i].className = "";
else childElems[i].className = "active";
if(childElems[i]==object) currElemSet = true;
}
}
}
}
catch(e)
{
alert("Error: " + e.Message);
}
finally
{
}
}
How to get a HTML element by searching the content of innerHTML?
For example, Search
I want to get the "a" tag by searching word "Search" using javascript.
Thank you
var aTags = document.querySelectorAll('a');
var searchaTag = '';
for(i = 0; i<aTags.length; i++ ) {
if(aTags[i].text == 'Search') {
searchaTag = aTags[i];
break;
}
}
If you have no idea where the element can be, iterate over each element:
var all = document.querySelectorAll('*'); //OR document.getElementsByTagName("*")
for(var i = 0; i < all.length; i++ ) {
if(all[i].innerHTML === "search") {
console.log(all[i].tagName);
}
}
If you have some clue you can narrow your search by looking inside that area:
var all = document.querySelector('#my-Container').getElementsByTagName('*');
I'm trying to loop through an Array which then uses innerHTML to create a new element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
window.onload = function() {
// Read value from storage, or empty array
var names = JSON.parse(localStorage.getItem('locname') || "[]");
var i = 0;
n = (names.length);
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
}
I have a UL with the id 'list' in my HTML.
Change your for loop:
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
Use += instead of =. Other than that, your code looks fine.
I suggest you to first make a div by create element. there you add your innerHTML and after that you can do the appendchild. That will work perfectly for this type of scenario.
function displayCountries(countries) {
const countriesDiv = document.getElementById('countriesDiv');
countries.forEach(country => {
console.log(country.borders);
const div = document.createElement('div');
div.classList.add('countryStyle');
div.innerHTML = `
<h1> Name : ${country.name.official} </h1>
<h2> Capital : ${country.capital} </h2>
<h3> Borders : ${country.borders} </h3>
<img src="${country.flags.png}">
`;
countriesDiv.appendChild(div);
});
}
I want to have my page's html to appear as:
<div class='container'>
<div class='domain-list0'>Hello</div>
<div class='domain-list1'>World</div>
</div>
Here is my html and js: Pen from Codepen.io
Instead of creating the first "domain-list" and then creating another one for the next, it is just overwriting the previous "domain-list". This is why it shows the last string value. Anyone know how to fix this?
Thanks!
You are using .html() which removes the existing content, and replaces it with the new content. You need to use append so that the new content is added after the last child.
var myStringArray = ["Hello", "World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
var $el = $("<div />", {
'class': 'domain-list' + i,
html: "<p>" + myStringArray[i] + "</p>"
}).appendTo("div.container");
// $el refer to the newl added element
}
Demo: Fiddle
use .appendTo() so that it will return the newly created element which can be used for further processing
for (var i = 0; i < arrayLength; i++) {
$("div.container").html("<div class='domain-list'></div>");
$(".domain-list:nth-child("+i+")").html("<p>"+myStringArray[i]+"</p>");
//Do something
}
Try to use appendTo in jquery
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
$("<div class='domain-list"+i+"'></div>").html("<p>"+myStringArray[i]+"</p>").appendTo("div.container");
//Do something
}