elementNodeReference.children doesn't detect text nodes? - javascript

Per this link returns a list of child nodes. In my testing this seems to ignore text nodes. Is this correct?
What seems baffling to me is that firstChild works but the children list is zero.
Tested in Firefox 20.0.1.
Here's my test code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title></title>
<script>
function checktable() {
var mytable = document.getElementById("mytable");
var cells = mytable.rows[0].cells;
for (var i = 0; i < cells.length; i++) {
console.log("firstChild.nodeValue:", cells[i].firstChild.nodeValue);
console.log("firstChild.data:",cells[i].firstChild.data);
console.log("children.length:",cells[i].children.length);
}
}
function checkdiv() {
var mydiv = document.getElementById("mydiv");
console.log("firstChild.nodeValue:", mydiv.firstChild.nodeValue);
console.log("firstChild.data:",mydiv.firstChild.data);
console.log("children.length:",mydiv.children.length);
}
</script>
<style>
</style>
</head>
<body>
<table id="mytable">
<tr>
<td>Blob</td>
<td>Blab</td>
<td>Link</td>
</tr>
</table>
<div id="mydiv">
Blib
</div>
<button onclick="checktable()">Check table</button>
<button onclick="checkdiv()">Check div</button>
</body>
</html>

You want .childNodes, not .children.
The former is a method of Node and lists child nodes. The latter is a method of Element and consequently lists child elements, which is preferable in some situations.

Related

External Javascript doesn't load in VSCode

I'm working in VSCODE. I have an html page and I want to include an external javascript file in it.
this is the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Exercise</title>
<link rel="stylesheet" href="./assets/css/styles.css">
</head>
<body onload="addTable()">
<div class="title">Reports</div>
<!-- singolo run test -->
<div class="block">
<h1> Ultimo test eseguito </h1>
<div id="myDynamicTableTitles" class="table"></div>
<div id="myDynamicTable" class="table"></div>
</div>
<!-- JAVASCRIPT -->
<script src="./index.js"></script>
</body>
</html>
I know for sure that the js I wrote works, because if I put the js directly inside the <script></script> the page works.
Any idea on why, if I put it into an external file, it doesn't load? I'm also sure that the path "./index.js" it's correct.
I've noticed that if I click directly on the file html it works (like from the computer explorer). But if I load the project trough VSCode, it doesn't.
when I execute npm start it compile and gives me an http://localhost:xxxx
To make an example...
Maybe the script have an error?
function addTable(table) {
//Maybe you miss something? Here's an example
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < 2; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell in row "+i+", column "+j);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Exercise</title>
<link rel="stylesheet" href="./assets/css/styles.css">
</head>
<body onload="addTable()"></body>
<div class="title">Reports</div>
<!-- singolo run test -->
<div class="block">
<h1> Ultimo test eseguito </h1>
<div id="myDynamicTableTitles" class="table"></div>
<div id="myDynamicTable" class="table"></div>
</div>
<!-- JAVASCRIPT -->
<script src="./index.js"></script>
<!-- add this -->
</body>
</html>
You can find more explanations of this JScode in this great page
Divertiti
I've noticed that if I click directly on the file html it works (like from the computer explorer). But if I load the project trough VSCode, it doesn't.
It sounds like you are using the Live HTML Previewer extension which says:
Note: Javascript is not supported in preview
Use a browser to test your browser-dependant JS.

Why Is a "for" Loop Needed to Make This Onclick Mechanism Work?

The code is supposed to create two buttons that produce a paragraph once clicked. Although the function to create a paragraph works, the buttons do not trigger the function.
The HTML is as follows, which I believe is correct.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Apply JavaScript example</title>
<script src="scripts/t.js" defer></script>
</head>
<body>
<button>Click 1</button>
<br>
<button>Click 2</button>
</body>
</html>
JS#1:
`function createParagraph() {
let paragraph = document.createElement('p');
paragraph.textContent = 'text';
document.body.appendChild(paragraph);
}
const buttons = document.querySelectorAll('button');
buttons.onclick = createParagraph();
`
JS#2: After seeing that it did not work, I changed the last line to buttons.addEventListener('click', createParagraph);, which led to no solution.
This document suggests the following code
`for(let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', createParagraph);
}`
, the complexity/length of which led me to seek a simpler approach.
I do not understand how the last code works but JS#1 and JS#2 do not.
You can see the entire (working) code in action below:
function createParagraph() {
let paragraph = document.createElement('p');
paragraph.textContent = 'text';
document.body.appendChild(paragraph);
}
const buttons = document.querySelectorAll('button');
for(let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', createParagraph);
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Apply JavaScript example</title>
<script src="scripts/t.js" defer></script>
</head>
<body>
<button>Click 1</button>
<br>
<button>Click 2</button>
</body>
</html>
querySelectorAll() returns a NodeList so you need to iterate through all of them in order to call the addEventListener method of every element.
You cannot call method addEventListener on a NodeList.

Flickering when appending row to table JQUERY

I have read all the other articles and none seem to have helped.
The page in question is www.projectwhisper.net78.net
When the button is clicked, a row is added.
But if you look carefully, there is a flicker near the bottom of the table.
Here is the HTML of the page:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<p>Hi There!</p><button id="the_button">Click to add row</button>
<table id="content"><tbody></tbody>
</table>
<script type="text/javascript">
$("#the_button").click(function()
{
var row=$("<tr><td>This is a row</td></tr>");
row.hide()
row.prependTo('table > tbody');
row.slideDown(500);
});
</script>
</body>
</html>
DEMO
Try this
$("#the_button").click(function () {
var row = $("<tr><td>This is a row</td></tr>");
row.prependTo('table > tbody').hide();
row.show(500);
});
Each time the row is added to the top of the table tbody as a stack, since each element is prepended to the table tbody

Dynamically assign class to paragraph

How do you assign a class dynamically to a paragraph (via javascript/CSS) IF the paragraph contains the wording "Time Recorded:"?
You'll notice that I have manually assigned the paragraph with class class="dyncontent".
However, I'd like to dynamically assign this class to any paragraph tag which contain the words "Time Recorded:".
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script type="text/javascript">
if (document.all || document.getElementById){ //if IE4 or NS6+
document.write('<style type="text/css">')
document.write('.dyncontent{display:none;}')
document.write('</style>')
}
</script>
<div class="right">
<ul>
<li class="say agent public">
<p>Description line 1</p>
<p class="dyncontent">Time Recorded: 5MIN(S)</p>
<p>Another description line</p>
</li>
</ul>
</div>
</body>
</html>
You could use jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(function(){
$("p:contains('Time Recorded:')").addClass('dyncontents');
});
</script>
$("p").each(function(ele) {if (this.html().indexOf('TimeRecorded') > 1) {$(this).addClass('dyncontent'))}});
I'd do indexOf because it will match easier than innerText
var allP = document.getElementsByTagName('p'),
pLength = allP.length;
while(pLength--){
if(allP[pLength].innerHTML.indexOf('Time Recorded') != -1){
allP[pLength].addClass('dycontents');
}
}
To explain: first you get all the <p> in the document. Then you loop through them. If any of them contain text of Time Recorded you add your class to it.
The following is solution without Jquery
o = document.getElementsByTagName('p');
for (i = 0; i < o.length; i++) {
if (o[i].innerText.indexOf('Time Recorded:') != -1) {
o[i].className = 'theClassYouWant';
}
}

HTML Dom manipulation: IE7 issue

Why this sample of code doesn't work on IE7. Where is the problem? Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Test</title>
<script language="javascript" type="text/javascript">
function initialize()
{
for(var i=0; i < 10; i++)
{
var tab = document.getElementById("search").childNodes[0];
var line = document.createElement("tr");
var column = document.createElement("td");
column.appendChild(document.createTextNode("DATA"));
line.appendChild(column);
tab.appendChild(line);
}
}
</script>
</head>
<body onload="initialize()">
<div id="search" class="bulle"><table><tr><td></td><td align="right">X</td></tr><tr><td><table id="tableResult"><table></td><td></td></tr></table></div>
</body>
</html>
In IE you must add table rows to the tbody, not directly to the table. Also, in some browsers the first child of the div will be a text node if there is any whitespace between the DIV and TABLE tags in the markup. So either move the id to the table (or a tbody element), or use:
function initialize() {
var div = document.getElementById("search");
var tbody = div.getElementsByTagName('tbody')[0];
// create rows, cells, etc.
tbody.appendChild(line);
}
Note that all tables with rows will have a tbody element, even though the tags are optional in the markup (i.e. your markup doesn't have a tbody element, but the table in the DOM will have one).
There is a tutorial on MDN about using the DOM table methods: https://developer.mozilla.org/en/Gecko_DOM_Reference/Examples#Example_8:_Using_the_DOM_Table_Interface.

Categories