forEach method not setting style property for list items - javascript

Here is app.js
const listItems=document.querySelector(".student-list").children;
const numberOfItems=10;
const page=document.querySelector(".page");
displayPage=(list,pageNumber)=> {
const SI=(pageNumber*numberOfItems)-numberOfItems
const EI=pageNumber*numberOfItems
Array.of(list).forEach((item,index)=> {
if (index>= SI && index<EI) {
item.style.display="block";
} else {
item.style.display="none";
}
})
}
addPaginationLinks=(list)=> {
const pages=list.length/10
let html=``
for (let i=0; i<pages; i++) {
html+=`
<li>
<a class="active" href="#">${i+1}</a>
</li>`
return html
}
ul=document.createElement("UL");
ul.innerHTML=html;
div=document.createElement("DIV");
div.className.add("pagination");
div.appendChild(ul);
page.appendChild(div);
}
displayPage(listItems, 1);
addPaginationLinks(listItems);
Here is a sample of index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Students</title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/design.css">
</head>
<body>
<div class="page">
<div class="page-header cf">
<h2>Students</h2>
<!-- dynamically insert search form here (optional) -->
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
There's no error in the html, it just continues down with more and more li's, and then closes up with a ul and a closing div tag. Then the script app js appears later.
I'm getting an Uncaught TypeError: Cannot set property 'display' of undefined Array.forEach
Basically, it's not recognizing each item in the list in the for each loop. Why is that? When I console log the items, the HTML collection shows up.

Related

jQuery load executes but callback is not executed

I am kinda new to website development, so I am asking for some help on the matter. I have the following snippet of html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--CSS Styles -->
<link rel="stylesheet" href="../assets/css/styles.css"/>
</head>
<body>
<!--Navigation bar-->
<div id="nav-placeholder"></div>
<!--end of Navigation bar-->
</body>
<script src="../assets/js/navigation_bar.js" type="text/javascript", locator="about"></script>
</html>
It calls the navigation_bar.js script provided here
locator = document.currentScript.getAttribute('locator');
function changeActiveElement(element_id){
console.log("Called");
nav_element = document.getElementById("navigation");
for (i = 0; i < nav_element.length; i++) {
console.log(nav_element[i].id)
if(nav_element[i].id == element_id) document.getElementById(element_id).className = "active-nav-link";
else document.getElementById(element_id).className = "nav-link";
}
}
$(function()
{$("#nav-placeholder").load("/assets/html/nav.html", function(){
changeActiveElement(locator);
});}
);
whereas the nav.html file is here:
<nav>
<h1>Some name</h1>
<ul id="navigation" class="navigation">
<li><a id="about" href="/pages/about.html" class="nav-link">About</a></li>
<li><a id="compt" href="#compt" class="nav-link">Competences</a></li>
<li><a id="projects" href="#projects" class="nav-link">Projects</a></li>
<li><a id="contact" href="#contact" class="nav-link">Contact</a></li>
</ul>
<button class="burger-menu" id="burger-menu">
<ion-icon class="bars" name="menu-outline"></ion-icon>
</button>
</nav>
The scope of the snippet is to change the class of the a tags listed in the navigation element. The navigation bar is correctly loaded via $("#nav-placeholder").load("/assets/html/nav.html"), yet changeActiveElement function is never executed via the callback.
Can someone explain me this behaviour?
I tested your code and everything is working except that nav_element is not a list and therefore nav_element.length throws an error. You could use document.querySelectorAll("#navigation"); instead, which returns a node list of all selected elements. Although, I would not recommend doing a for loop on elements by id. Use classes to select the elements. Id is only for one element.

I want to make a todo list but I am stuck at the start, where am I going wrong in this code?

I want to add li to the ul element with the value entered by user in the input area.
This is the error I am getting in console:
[Error] TypeError: document.getElementsByClassName("list-group").appendChild is not a function. (In 'document.getElementsByClassName("list-group").appendChild("li")', 'document.getElementsByClassName("list-group").appendChild' is undefined)
additem (script.js:7)
//this is my javascript code-->
function additem() {
var task = document.getElementsByClassName("input-group-text").value;
var li = document.createElement("li");
li.classList.add("list-group-item");
li = "task";
document.getElementsByClassName("list-group").appendChild("li");
}
document.getElementById("button").addEventListener("click",additem);
//<--!this is my html code-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LearnCodeOnline</title>
<link rel="stylesheet" href="./style.css" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
/>
</head>
<body class="bg-dark">
<div class="container bg-warning p-4">
<h1 class="text-center">LearnCodeOnline</h1>
<div class="input-group">
<span class="input-group-text">todo</span>
<textarea class="form-control" aria-label="With textarea"></textarea>
</div>
<button id="button" class="float-right">Add</button>
<ul class="list-group">
<li class="list-group-item">An item</li>
</ul>
<!-- <button
type="button"
class="btn btn-success btn-lg mt-4 mx-auto d-block sort-btn"
>
Sort courses
</button> -->
</div>
</body>
</html>
JS:-
function additem() {
var task = document.getElementsByClassName("form-control")[0].value;
var li = document.createElement("li");
li.classList.add("list-group-item");
li.innerText = task;
document.getElementsByClassName("list-group")[0].appendChild(li);
}
document.getElementById("button").addEventListener("click",additem);
Instead of doing .appendChild("li"), we'll give it an element and not string as it takes the element and not string
getElementsByClassName() returns an array so we will take the item at 0th index of the array in both the functions where it is there
also instead of setting li = "task" like this, we'll have to set its text by li.innerText = task

How to add popover to dynamically created list items

I have the following code. Clicking on the existing list item shows the popover.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$('[data-toggle="popover"]').popover()
})
</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.0/dist/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
<div class="card" style="width: 18rem;">
<div class="card-header">
Featured
</div>
<ul id="card-list" class="list-group list-group-flush">
<li id="card-item" class="list-group-item" data-toggle="popover" title="Rule Details" data-placement="top" data-html="true" data-content="<h3>Popover Content</h3>">Cras justo odio</li>
</ul>
</div></br>
<button id="test" type="button" class="btn btn-outline-dark btn-sm">Test</button>
</div>
</body>
</html>
The above code has a Test button to add items to the current list. I use the code below to define new items during which I set popover attributes. New list items can be added but clicking on them doesn't bring up popovers. Please help!
let listItem = document.createElement('li');
listItem.innerHTML = "Test";
listItem.className = "list-group-item";
listItem.setAttribute("data-toggle", "popover");
listItem.setAttribute("title", "Rule Details");
listItem.setAttribute("data-placement", "top");
listItem.setAttribute("data-html", "true");
listItem.setAttribute("data-content", "<strong>test Hello World</strong>");
document.getElementById("card-list").appendChild(listItem);
You have to initialize popover on the newly created elements. Since popover is a jQuery plugin convert your element to jQuery object and apply popoper before appending like:
let listItem = document.createElement('li');
listItem.innerHTML = "Test";
listItem.className = "list-group-item";
listItem.setAttribute("data-toggle", "popover");
listItem.setAttribute("title", "Rule Details");
listItem.setAttribute("data-placement", "top");
listItem.setAttribute("data-html", "true");
listItem.setAttribute("data-content", "<strong>test Hello World</strong>");
listItem = $(listItem);
listItem.popover();
$("#card-list").append(listItem);

Element.insertAdjacentHTML() API throws error in chrome 55.0.2883.87

I found the explaination about the API here, which tells me the second parameter is a string.
It's perform normal in firefox. However, in chrome, it shows the errors below:
I just curious about what makes this? Is it because the api is still stay Working Draft status and different browsers do the different implementation?
The following is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div">
<ul>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
</ul>
</div>
<script>
//normal
// var pTag=document.createElement("p");
// div.insertAdjacentElement("beforeend",pTag);
//throw error:
// Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.
var txt = "<p>testtest</p>";
div.insertAdjacentElement("beforeend",txt);
</script>
</body>
</html>
Just Change div.insertAdjacentElement to div.insertAdjacentHTML:
<!-- <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Coding revoltion</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="parent">
<ul class="ul"></ul>
</div>
<script src="dom.js"></script>
</body>
</html>
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div">
<ul>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
</ul>
</div>
<script>
//normal
// var pTag=document.createElement("p");
// div.insertAdjacentElement("beforeend",pTag);
//throw error:
// Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.
var txt = "<p>testtest</p>";
div.insertAdjacentHTML("beforeend",txt);
</script>
</body>
</html>
The parameters are incorrect. The second parameter should be html element, in your case it's a string.
Your txt variable must be an element. You can try this :
var txt = document.createElement("p")
txt.innerHTML = "testtest";
div.insertAdjacentElement("beforeend",txt);
There are two methods to insert new block of elements :
insertAdjacentElement(position, element)
The second parameter should be an element and not html text.
E.g.
var newDiv = document.createElement('div');
newDiv.style.backgroundColor = 'white';
parentElement.insertAdjacentElement('beforeend',newDiv);
insertAdjacentHTML(position, text)
text is valid html text or xml.
e.g.
var newDiv = `<div>This is a new div</div>
<p> Hello !! </p>`;
parentDiv.addAdjacentHTML('beforeend',newDiv);
first create a new html element programatically var htmlObject = document.createElement('div'); then assign your string to newly created object htmlObject.innerHTML=htmlString;.
var htmlString = `<div class="item clearfix" id="income-${obj.id}">
<div class="item__description">${obj.descripiton}</div>
<div class="right clearfix">
<div class="item__value">${obj.value}</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>`
var htmlObject = document.createElement('div');
htmlObject.innerHTML=htmlString;
document.querySelector(".income__list").insertAdjacentElement('beforeend', htmlObject);
You can use either Obj.innerHTML or Obj.insertAdjacentHTML() if you want to continue with String HTML
const html = `
<li>enter code here
<div class="collapsible-header grey lighten-4">${ title }</div>
<div class="collapsible-body white">${ content }</div>enter code here
</li>
`;
PARENTELEMENT.insertAdjacentHTML('beforeend', html);
I have change div.insertAdjacentElement to div.insertAdjacentHTML:
and it will work for me

how to load an external html file that contains scripts

Unfortunately, I am not sure to understand anything to java, jquery and all this kind of thing. Nevertheless, I am trying to get some inspiration on forums in order to make a personal website that contains a vertical navbar and a div container in which external html pages will be loaded. Each html file uses an html5 applet called JSmol, which plots 3D molecules that can be manipulated interactively. The main page looks like this:
<!DOCTYPE html>
<html>
<head>
<title> 3D Chemistry </title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="Chem3D-CSS/MolChem.css" />
<link href='http://fonts.googleapis.com/css?family=Archivo+Narrow' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<!-- META TAGS start -->
<meta name="Title" content="Molecular Chemistry" />
<meta charset="UTF-8">
<!-- META TAGS end -->
<script type="text/javascript">
$(document).ready(function() {
// select all the links with class="lnk", when one of them is clicked, get its "href" value
// load the content from that URL and check the "status" of the request
// place the response or an error message into the tag with id="content"
$('a.lnk').click(function() {
var url = $(this).attr('href');
$('#content').load(url, function(response, status, xhr) {
// check the status, if "success", place the response into #content
// else, if "error", define an error message and insert it into #content
// else, display an Alert with the status
if(status=='success') {
$('#content').html(response);
}
else if(status=='error') {
var ermsg = '<i>There was an error: '+ xhr.status+ ' '+ xhr.statusText+ '</i>';
$('#content').html(ermsg);
}
else { alert(status); }
});
return false;
})
});
</script>
</head>
<body class="s_page" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div id="header"> <a id="UPS-link" href="http://www.univ-tlse3.fr/" title="Paul Sabatier University - Toulouse III">
<img src="Chem3D-IMAGES/UT3_PRES_logoQ.png" alt="Paul Sabatier University" id="logoUPS" width=300px />
</a>
</div>
<div id="vmenu">
<ul>
<li>Home</li>
<li>3D Molecules
<ul>
<li>Mol1</li>
<li>Mol2</li>
</ul>
</li>
<li>Symmetry
<ul>
<li>Symmetry Elements
<ul>
<li>C<sub>2</sub>H<sub>6</sub></li>
<li>Ru<sub>4</sub>H<sub>4</sub>(CO)<sub>12</sub></li>
</ul>
</li>
<li>Point Groups
</li>
</ul>
</li>
<li>Solids
<ul>
<li>fcc</li>
<li>hcp</li>
</ul>
</li>
</ul>
</div>
<div id="content">
</div>
<div class="s_author" id="footer">
author: romuald.poteau_at_univ-tlse3.fr
<br/>last modification: 2013/12/16
</div>
</body>
</html>
Up to now, I have worked on the PG.html file (Point Group entry in the vertical menu), which works perfectly fine when it is loaded separately. But is not the case when it is loaded inside the main page as an external html page. The title is the only thing that appears, it seems that the jsmol application is not properly initialized. May be this is specific to the invocation of jsmol ; or is this a general issue when one wants to load hmtl files with embedded scripts ?
<!DOCTYPE html>
<html>
<head>
<title> POINT GROUPS </title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="Chem3D-CSS/MolChem.css" />
<!-- META TAGS start -->
<meta name="Title" content="Molecular Chemistry" />
<meta name="Format" content="text/html" />
<meta name="Language" content="en" />
<meta charset="UTF-8">
<!-- META TAGS end -->
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="./JSmol.min.js"></script>
<script type="text/javascript">
// ---------------------------------------------------------------------------------
////// every page will need one variable and one Info object for each applet object
var Info = {
width: 500,
height: 500,
color: "0xC0C0C0",
use: "HTML5",
jarPath: "java",
j2sPath: "j2s",
jarFile: "JmolApplet.jar",
isSigned: false,
addSelectionOptions: false,
serverURL: "php/jsmol.php",
readyFunction: jmol_isReady,
console: "jmol_infodiv",
disableInitialConsole: true,
debug: false,
}
</script>
</head>
<body class="s_page" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div class="s_title" id="titlePG">
Point Groups
</div>
<div class="s_normal" id="mainPG">
<table border="0">
<tbody>
<tr valign="top">
<td nowrap="nowrap">
<script type="text/javascript">
Jmol.getApplet("Jmol1", Info);
Jmol.script(Jmol1,'load Chem3D-data/nh2cl.xyz;');
Jmol.resizeApplet(Jmol1, 500);
</script>
<br>
</td>
<td>
<script>
Jmol.setButtonCss(null,"style='width:300px'")
Jmol.jmolButton(Jmol1,"load Chem3D-data/nh2cl.xyz;", "NH2Cl (Cs)");
Jmol.jmolBr();
Jmol.jmolButton(Jmol1,"load Chem3D-data/cis-dichloroethylene.xyz;", "cis-dichloroethylene (C2v)");
Jmol.jmolBr();
Jmol.jmolButton(Jmol1,"load Chem3D-data/trans-dichloroethylene.xyz;", "trans-dichloroethylene (C2h)");
</script>
<br>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
I have tried to find an answer to this question by checking previous posts, but my poor skills do not allow me to identify relevant suggestions for such issue.
Thanks for any help.
// Create a DOM object from a URL
$html = file_get_html('http://www.google.com/');
// Create a DOM object from a HTML file
$html = file_get_html('test.htm');

Categories

Resources