Where is nodeValue for body.childNodes? - javascript

I runs this Javascript code and get nodeType and nodeName without problem for the body.childNode. However, nodeValue fail to display.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the node types of the body element's child nodes.</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> Whitespace inside elements is considered as text, and text is considered as nodes.</p>
<!-- My personal comment goes here.. -->
<div><strong>Note:</strong> Comments in the document are considered as comment nodes.</div>
<p id="demo"></p>
<script>
function myFunction() {
var c = document.body.childNodes;
var txt = "";
var i;
for (i = 0; i < c.length; i++) {
txt = txt + "notdType: "+ c[i].nodeType + " NodeName: "+c[i].nodeName+" NodeValue: "+c[i].nodeValue +"<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

Element nodes don't have node values. Instead, they have child nodes of their own.

Related

I want to replace . with <br>tag using javascript

I've tried this
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some random text. random text</p>
<button type="button" onclick="strReplace();">Replace</button>
<script>
function strReplace(){
var myStr = document.getElementById("text");
var mySte = myStr.textContent;
console.log(mySte);
</script>
</body>
and I want this following outcome
just some random text
random text
You can use this regex to find and replace string without breaking html: /(?!<[^>]+)\.(?![^<]+>)/g
[myattr]
{
background-color: pink;
}
[myattr]:after
{
content: "this element's attribute is: " attr(myattr);
background-color: lightgreen;
margin: 1em;
}
p > span
{
background-color: lightblue;
}
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some. random text. <span myattr="text.with.dots">nested.html</span> end.
<span>i < 40. But i is also > 30. What are valid values of i?</span>
</p>
<button type="button" onclick="strReplace();">Replace</button>
<script>
function strReplace(){
var myStr = document.getElementById("text");
myStr.innerHTML = myStr.innerHTML.replace(/(?!<[^>]+)\.(?![^<]+>)/g, "<br>");
console.log(myStr.innerHTML);
}
</script>
</body>
To directly answer the question:
var outputHtml = inputText.replace(/\./g, '<br />');
The Javascript replace method will by default replace the first instance of something (the first . in this case), so the g regex modifier tells it to replace them all. The \. in the regex is because . is a special character in regexes. This will replace every dot in the text.
What about ellipsis?
This technique won't work well on text that contains literal ellipsis, like this:
Hello world...
If your text is likely to contain this, and you want that to be ignored, then the following regex is more appropriate:
/[^\.](\.)[^\.]/g
This'll match any . which is not surrounded by other .
var outputHtml = inputText.replace(/[^\.](\.)[^\.]/g, '<br />');
Handling HTML
In the question here, the input is actually coming from the DOM. We can't replace . on its innerHTML as it would replace content inside HTML tags as well. So, if your input text is coming from the DOM like this (and not, say, a textarea), then the safest route is to apply the replacement only to text nodes. That is done like this:
document.getElementById("start").addEventListener("click", () => {
var inputNode = document.getElementById("text");
replace(inputNode);
});
function replace(node) {
if(!node) {
return;
}
if (node.nodeName == '#text') {
// We've found a text node. Apply the regex to it now.
// Note that you can use either of the above regexes here.
var inputText = node.textContent;
var lines = inputText.split(/\./g);
if(lines.length > 1) {
// It had at least one dot in it.
// Swap in this new set, each with a <br /> between them.
var parent = node.parentNode;
var nextSibling = node.nextSibling;
parent.removeChild(node);
lines.forEach((line, i) => {
if(i != 0){
// insert the <br>
var br = document.createElement('br');
parent.insertBefore(br, nextSibling);
}
var textNode = document.createTextNode(line);
parent.insertBefore(textNode, nextSibling);
});
}
} else {
// Loop through each child node.
// We go backwards such that completed replacements don't affect the loop.
for(var i=node.childNodes.length - 1; i>=0; i--) {
replace(node.childNodes[i]);
}
}
}
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some random text. random text</p>
<button type="button" id="start">Replace</button>
</body>
</html>
If you're starting from a HTML string inside a browser, you can then use the above replace method and the browsers internal parsing to safely only affect the actual text:
function replaceHtmlString(html) {
var div = document.createElement('div');
div.innerHTML = html;
replace(div);
return div.innerHTML;
}

Uncaught TypeError from generated JavaScript elements

I'm generating a dynamic list of from/inputs and buttons from JSON. The button triggers a JavaScript function that reads the current content of the input in a form. However when the button is clicked I get the following error code Uncaught TypeError: Cannot read property '0' of undefined.
This tells me there are no elements in the form but I don't know why. Tryed 0-3 just to make sure.
Length also return undefined. I am able to edit the innerHTML of the form.
A striped down code I'm trying to get a value from.
<!DOCTYPE html>
<html>
<body onload="gen_form()">
<div id="connectResult"></div>
<p id="demo">RESULT HERE</p>
<script>
const connect_result = document.getElementById("connectResult");
function gen_form(){
var div = document.createElement("DIV");
div.setAttribute("id", "div0");
div.innerHTML += "sometxt<br/>";
var form1 = document.createElement("FROM");
form1.setAttribute("id", 'form_sometxt2_0');
var input1 = document.createElement("input");
input1.setAttribute("type",'text');
input1.setAttribute("name",'textbox');
form1.appendChild(input1);
div.appendChild(form1);
var btn4 = document.createElement("BUTTON");
btn4.setAttribute("id", 'WRITE_sometxt2_0');
btn4.innerHTML = 'WRITE';
btn4.setAttribute("onclick", "myFunction(this)");
div.appendChild(btn4);
connect_result.appendChild(div);
}
function myFunction(param) {
var text = document.getElementById("form_sometxt2_0").elements[0].value + "<br>";
document.getElementById("demo").innerHTML = text;
}
</script>
</html>
The following does exactly what I want but it is static. The above is based off this.
<!DOCTYPE html>
<html>
<body>
<form id="frm1">
<input type="text">
</form>
<button onclick="myFunction()">Try it</button>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var text = document.getElementById("frm1").elements[0].value + "<br>";
document.getElementById("demo").innerHTML = text;
}
</script>
</html>
My question is: What is the difference between these two code snippets and how do I fix said error?
I would prefer not to use a submit input as there will be a second button that edits the contents of the input value.
PS: I'm fairly new to JavaScript and its terminology.
Using Chrome as my debugger.
Tipo error.comment
var form1 = document.createElement("FROM");
should be:
var form1 = document.createElement("FORM");

How can i return 2 values with getElementsByClassName()? [duplicate]

This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 6 years ago.
<!DOCTYPE html>
<html>
<body>
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
Link for example: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementsbyclassname
This example show us how to change first div to "hello world". I wanna learn how can i change all classes to "Hello world". I tried to change x[0].innerHTML = "Hello World!"; to x[*].innerHTML = "Hello World!"; but nothing happened. Any idea? :/
Use loop as:
<!DOCTYPE html>
<html>
<body>
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
for(var i = 0; i < x.length; i++)
x[i].innerHTML = "Hello World!";
}
</script>
</body>
</html>
You have to use a loop in order to affect all of the elements:
function myFunction() {
var x = document.getElementsByClassName("example");
for (var i = 0; i < x.length; i++)
x[i].innerHTML = "Hello World!";
}
You can use querySelectorAll method:
function myFunction() {
var divs = document.querySelectorAll('.example');
[].forEach.call(divs, function(div) {
div.innerHTML = "Hello World!";
});
}

Trouble getting real time word count from html textbox

I am very new to html and javascript. I have a textbox and am trying to count the number of words, then displaying the count in real time. I do not understand what I am doing wrong in this, or how to correct it. textContent does not make much sense to me.
<html>
<head>
<style>
input[type='text'] {width:50px;}
textarea {width:500px;height:300px;}
</style>
</head>
<body>
<div>
<h2>Test</h2>
<p>The number of words is <span id="wordCount"></span></p>
<textarea id="toCount"></textarea>
</div>
<script>
document.getElementById('toCount').addEventListener('input', function () {
var text = this.textContent,
count = text.trim().replace(/\s+/g, ' ').split(' ').length;
document.querySelector('.wordCount').textContent = count;
});
</script>
</body>
</html>
The error that I get right now says
Uncaught TypeError: Cannot set property 'textContent' of null
Your selector should be #wordCount, and the textarea content can be accessed using value:
<html>
<head>
<style>
input[type='text'] {width:50px;}
textarea {width:500px;height:300px;}
</style>
</head>
<body>
<div>
<h2>Test</h2>
<p>The number of words is <span id="wordCount"></span></p>
<textarea id="toCount"></textarea>
</div>
<script>
document.getElementById('toCount').addEventListener('input', function () {
var text = this.value,
count = text.trim().replace(/\s+/g, ' ').split(' ').length;
document.getElementById('wordCount').textContent = count;
});
</script>
</body>
</html>
The reason why you are getting null is: in selection, #wordCount is by Id, and .wordCount is by class. So document.querySelector('.wordCount') is returning null as there is no element with class wordCount.
The fix would be to simply change
document.querySelector('.wordCount').textContent = count;
to
document.querySelector('#wordCount').textContent = count;
Try this one.
document.getElementById('toCount').addEventListener('input', function () {
// var text = this.textContent,
var text = this.value,
count = text.trim().replace(/\s+/g, ' ').split(' ').length;
// document.querySelector('#wordCount').textContent = count;
document.querySelector('#wordCount').textContent = count;
});
try this.
document.getElementById('toCount').addEventListener('input', function () {
var text = this.value,
count = text.trim().split(' ').length;
document.querySelector('#wordCount').textContent = count;
});
Here is the jsfiddle

Javascript change text of all inputs

I'm really newbie at Web Development and I'm trying to change the text of some inputs, with Javascript. Here is a example of what my code have to do
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x=document.getElementByTagName("input")
for(var i = 0; i < x.length; i++) {
var str=x[i].innerHTML;
var n=str.replace(",",".");
var n1 = n.replace("R$ ","");
document.getElementById("demo").innerHTML=n1;
}
}
</script>
</body>
</html>
So, I want to withdraw the "R$" and replace "," to "." for some math operations. And I have to do this with all inputs in my code.
You were nearly there, replacing a few things to make it look similar to this:
function myFunction() {
var x = document.getElementsByTagName("input"); // ; was missing and you used getElementByTagName instead of getElementsByTagName
for (var i = 0; i < x.length; i++) {
var str = x[i].value; // use .value
var n = str.replace(",", ".");
var n1 = n.replace("R$ ", "");
//document.getElementById("demo").innerHTML=n1; // use x[i] again instead
x[i].value = n1; // and again use .value
}
}
DEMO - Running updated code
These are the needed steps - at least step 1 through 3
moved the script to the head where it belongs
changed getElementByTagName to getElementsByTagName, plural
get and change x[i].value
chained the replace
DEMO
<!DOCTYPE html>
<html>
<head>
<title>Replace example</title>
<script>
function myFunction() {
var x=document.getElementsByTagName("input"); // plural
for(var i = 0; i < x.length; i++) {
var str=x[i].value;
x[i].value=str.replace(",",".").replace("R$ ","");
}
}
</script>
</head>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
</body>
</html>
First of all, use .value instead of .innerHTML. .innerHTML referes to text within the opening and closing of the tag.
Secondly, correct the spellings at var x=document.getElementByTagName("input")
it should be getElementsByTagName
this function should do what you want:
function myFunction()
{
var eles=document.getElementsByTagName("input");
for(var i = 0; i < eles.length; i++)
{
if(eles[i].type != 'text') continue; // inputs that aren't of type text dont make sense here
var str = eles[i].value;
str=str.replace(",",".");
str=str.replace("R$ ","");
eles[i].value=str;
}
}

Categories

Resources