This code is attempting to highlight (by adding 'bold' tag) some characters that are in the HTML body. (These are specified in the JS function)
But instead of the text becoming bold, I get the 'bold' tag as the result in the html page that is getting rendered.
While I want some thing like
This is a test message
I get
This is a test <b>message</>
Any help would be awesome.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
The problem is that you are putting HTML in to a text node, so it is being evaluated strictly as text. One easy fix would be to simply operate on the innerHTML of the body element, like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var highLight = ['abcd', 'edge', 'rss feeds'],
contents = document.body.innerHTML;
for( i = 0; i < highLight.length; i++ ){
contents = delimiter(contents, highLight[i]);
}
document.body.innerHTML = contents;
}
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
A textNode cannot have child elements so it needs to be replaced, one way;
Replace
children[child].nodeValue = output;
With
var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);
Related
I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>
I cannot get my images to change when I click each button name. Anyone know what the issue is with my code?
It's not letting me put my code in the description.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hmwk02</title>
</head>
<body>
<h1>Octocats</h1>
<img id="octocats" src= "https://octodex.github.com/images/original.png" alt="octocat" width="150"/>
<div id="buttons"></div>
<script>
let names= ["Castello", "Grinchtocat", "Mummytocat", "Adventure-Cat"];
let urls= ["https://octodex.github.com/images/catstello.png",
"https://octodex.github.com/images/grinchtocat.gif",
"https://octodex.github.com/images/mummytocat.gif",
"https://octodex.github.com/images/adventure-cat.png"];
let lines = "";
for(let i = 0; i< names.length; i++){
lines += '<button onlick="showPicture(' + i +')">' + names[i] + '</button><br/>'
}
document.getElementById("buttons").innerHTML = lines;
console.log(lines);
</script>
<script src="octocats.js"></script>
</body>
function showPicture(i) {
document.getElementById("octocat").src = urls[i];
console.log(i);
}
Your code is fine other than syntax errors, you misspelled onclick in your button tag and you misspelled the ID for the picture--it should be document.getElementById("octocats") not document.getElementById("octocat")
corrected code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hmwk02</title>
</head>
<body>
<h1>Octocats</h1>
<img id="octocats" src= "https://octodex.github.com/images/original.png" alt="octocat" width="150"/>
<div id="buttons"></div>
<script>
let names= ["Castello", "Grinchtocat", "Mummytocat", "Adventure-Cat"];
let urls= ["https://octodex.github.com/images/catstello.png",
"https://octodex.github.com/images/grinchtocat.gif",
"https://octodex.github.com/images/mummytocat.gif",
"https://octodex.github.com/images/adventure-cat.png"];
let lines = "";
for(let i = 0; i< names.length; i++){
lines += '<button onclick="showPicture(' + i +')">' + names[i] + '</button><br/>'
}
document.getElementById("buttons").innerHTML = lines;
console.log(lines);
</script>
<script>
function showPicture(i) {
document.getElementById("octocats").src = urls[i];
console.log(i);
}</script>
</body>
working codepen: https://codepen.io/anon/pen/YBYxgr
An alternative to using the for loop would be to map() the names array and simply use createElement() method to create a new <button> element with a click listener for each item in your names array (you should avoid using inline on* handlers (onclick, oninput, etc) and use IDs and event listeners instead).
Check and run the following Code Snippet for a practical example of what I have described above:
let names= ["Castello", "Grinchtocat", "Mummytocat", "Adventure-Cat"];
let urls= ["https://octodex.github.com/images/catstello.png", "https://octodex.github.com/images/grinchtocat.gif", "https://octodex.github.com/images/mummytocat.gif", "https://octodex.github.com/images/adventure-cat.png"];
names.map((e, i) => { // add function to each element in "names" array
let name = document.createElement("button"); // create <button> element for each item in "names" array
name.id = i; // assign respective index as id of each element
name.textContent = e; // assign item string as button text content
name.addEventListener("click", () => document.getElementById("octocats").src = urls[i]); // add click listener to each <button> that changes image src on click
document.getElementById("buttons").appendChild(name); // append the <button> elements to your `#buttons` div.
});
<h1>Octocats</h1>
<img id="octocats" src= "https://octodex.github.com/images/original.png" alt="octocat" width="150"/>
<div id="buttons"></div>
I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari
I've a web page which include a JavaScript function to convert the multiple lines to a comma separated data. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add case</title>
<script type="text/javascript">
function replaceSeperator() {
var incident_box = document.getElementById("TextBoxIncidentID")
var content = incident_box.value;
//incident_box.innerHTML = content.replace(/\n/g, ",");
var ctt = content.replace(/\n/g, ",");
var lastchar = ctt.substr(ctt.length - 1);
if (lastchar != ",") {
incident_box.innerHTML = ctt;
} else {
incident_box.innerHTML = ctt.substr(0,ctt.length - 1);
}
}
</script>
</head>
<body>
<textarea name="TextBoxIncidentID" rows="2" cols="20" id="TextBoxIncidentID" textwrapping="Wrap" acceptreturn="true" onmouseout="replaceSeperator()" style="font-family:Calibri;font-size:Medium;height:60px;width:430px;margin-top: 5px;"></textarea>
</body>
</html>
It works fine in IE:
The line break replaced to comma
But it doesn't working as expected in Chrome and Firefox:
Line break replaced to comma at Dev Tool but it doesn't present on Chrome
Does any one know how to fix it?
Thanks
Use value property. innerHTML is for another purposes. Even textarea has the closing tag, the inner content is the textarea value:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add case</title>
<script type="text/javascript">
function replaceSeperator() {
var incident_box = document.getElementById("TextBoxIncidentID")
var content = incident_box.value;
//incident_box.innerHTML = content.replace(/\n/g, ",");
var ctt = content.replace(/\n/g, ",");
var lastchar = ctt.substr(ctt.length - 1);
if (lastchar != ",") {
incident_box.value = ctt;
} else {
incident_box.value = ctt.substr(0,ctt.length - 1);
}
}
</script>
</head>
<body>
<textarea name="TextBoxIncidentID" rows="2" cols="20" id="TextBoxIncidentID" textwrapping="Wrap" acceptreturn="true" onmouseout="replaceSeperator()" style="font-family:Calibri;font-size:Medium;height:60px;width:430px;margin-top: 5px;"></textarea>
</body>
</html>
You are missing a ; at the end of
var incident_box = document.getElementById("TextBoxIncidentID")
Some browsers are more forgiving to this than others.
I am learning JS and I am not yet familiar with internal workings. Can someone point out the error in my thinking?
The basic idea is to ask a complex question, construct the answer with JS (to a CSV syntax) and feed it to a textbox. (From here it will be processed to a db.) Example included below: How many children do you have? What is their names and age?
Perhaps, the new element generated by the first button is not added to the document? How to do this, or how to address the value in it?
How can I make the values submitted to previous lines stick in the event of adding a new line. For example 'Jack' and '10' is written to the first line, the user pressed the add new line, than this information should stay in the first line.
Incorrectly working example: The save button stops working if the code in the loop is added.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<script>
var lines = 0;
function addNew() {
lines++;
document.getElementById("qchildren-answer-wrapper").innerHTML += 'Gyermek neve:<input type="text" id="qchildrenname' + window.lines + '" /> Gyermek eletkora:<input type="text" id="qchildrenage' + window.lines + '" /><br/>';
}
function save() {
var answer = '';
for (var ii = 0; ii < window.lines; ii++) {
answer += document.getElementById('qchildrenname' + ii.toString()).value.toString() + ',' + document.getElementById('qchildrenage' + ii.toString()).value.toString() + ';';
}
document.getElementById("qchildren").value = answer;
}
< /script>
</body>
</html>
=Below code should work (AddNew function changed):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<script>
var lines=0;
function addNew()
{
lines++;
var newElement = document.createElement("span");
newElement.innerHTML = 'Gyermek neve:<input type="text" id="qchildrenname'+window.lines+'" /> Gyermek eletkora:<input type="text" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(newElement);
}
function save()
{
var answer='';
for (var ii=1;ii<=window.lines;ii++)
{
answer+=document.getElementById('qchildrenname'+ii.toString()).value.toString()+','+document.getElementById('qchildrenage'+ii.toString()).value.toString()+';';
}
document.getElementById("qchildren").value=answer;
}
</script>
</body>
</html>
Try code like this:
function addNew()
{
var div = document.createElement('div');
div.innerHTML = 'Gyermek neve:<input type="text" id="qchildrenname'+window.lines+'" /> Gyermek eletkora:<input type="text" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(div );
lines++;
}
Demo: http://jsfiddle.net/JByVg/8/
What happens in your case is that all previously created elements are recreated again because element.innerHTML += "some_html" is equal to element.innerHTML = element.innerHTML + "some_html" or, more clear, I suppose, var oldHtml = element.innerHTML;element.innerHTML = ""; element.innerHTML = oldHtml + "some_html"
Browser does not populate value="..." entered by user when you do var oldHtml = element.innerHTML and after += you have old elements recreated without values entered by user. At the same time, appendChild does not recreate old elements.
This example demonstrates how .innerHTML returns only initial HTML (I've added value="test" to your qchildrenname element code)