Delete children in Javascript DOM, console result different from in-page result - javascript

I was trying to dynamically delete all (dynamically added) children from a simple web page, and I found that when I click my button to run the JavaScript code in the web page, the resulting deletion is different than if I run the same code in the browser console.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="js/main.js"></script>
</head>
<body onclick="addText()">
<h1 id="my_text">Click on the page.</h1>
<button onclick="deleteText()">Click here to remove text node</button>
</body>
</html>
JavaScript:
function addText() {
newText = document.createTextNode("This is dynamically added text");
newText.id = "dynamicText";
var textPart = document.getElementById("my_text");
textPart.appendChild(newText);
}
function deleteText() {
var parent = document.getElementById("my_text");
while (parent.childNodes[1]) {
parent.removeChild(parent.childNodes[1]);
}
}
In the browser, I click on the header to dynamically append text nodes to the header. Then I wish to click the button to delete all the dynamically added text. When I click the button in the browser, it deletes all of the dynamically added text except one newText element, resulting in this:
Click on the page.This is dynamically added text
But, when I execute the same code ( or even just call the function deleteText() ) in the browser console, it deletes all newText elements as desired, resulting in this:
Click on the page.
I'm wondering, why is the result different when the code is executed from the browser window versus in the browser console? I'm using Chrome Version 46.0.2490.86 m

Its because when you click your "remove" button you are still clicking in the body tag, so the onclick in the <body> tag is still being triggered adding a text node again.

Related

Find and replace button works but takes me to a new page

I'm a beginner in JavaScript and I've been working on this project which uses regular expressions to find and replace particular strings on a text.
I'd say it's working pretty well, but when I click the 'go' button in order to replace the string, it does so, but takes me to a new page which only contains the replaced string. The console says something about "Quirks mode"? not sure what that is.
Here's my code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>findNreplace</title>
</head>
<body>
<textarea name="input" id="inputText">
</textarea>
<p id="projectedText"></p>
<label for="find">Find: </label>
<input type="text" id="find">
<label for="replace">Replace: </label>
<input type="text" name="" id="replace">
<input type="button" value="Go" id="commit">
<script src="script.js"></script>
</body>
</html>
document.getElementById("commit").onclick=findNreplace; //set up go button
//variables
var textToShow = document.getElementById("inputText");
var projected = document.getElementById("projectedText");
var toFind = document.getElementById("find");
var toReplace = document.getElementById("replace");
// set up text area to project the input into the paragraph
textToShow.addEventListener('input',updateValue);
function updateValue(text) {
projected.textContent=text.target.value;
}
// replace function
function findNreplace() {
var str = projected.innerText;
var regex = new RegExp(toFind.value, 'g')
var found = projected.innerText.match(regex);
document.write(str.replace(regex.source, toReplace.value))
console.log(regex.source);
}
;TLDR
Do not use document.write outside of a tutorial exercise to insert content into the HTML input stream during page load.
document.write, .open and .close
During page load, when the HTML parser is processing the HTML input stream, the document is open, and you can use document.write to insert content into the input stream at its current position.
When the page has finished loading from its input stream, the document is automatically closed.
If you call document.write on a closed document it will automatically open the document for you. This opening the document again resets the document to an empty state - of having no content. This is why you only see what you have written.
If the document is opened by document.write it will stay open until you explicitly call document.close. This is why if the browser displays a page loading indicator, it will remain active until document.close is called.
In most cases document.write is used in beginners' JavaScript programming course so they see results of example tasks quickly. It has a place in inserting HTML input during page load but has its limitations1.
Notes
1document.write can be used during page load to dynamically insert script tags that need to be loaded synchronously. Browsers sometimes ignore such insertions, but inserting scripts from the same domain as the HTML page is allowed.
See also Why is document.write considered a "bad practice"?
Quirks mode
The quirks mode warning is being issued because the HTML document does not start with a document type declaration. Insert the following line,
<!DOCTYPE html>
as the first line of HTML source to have the page parsed according to standards.
Appending HTML to a document.
Element.insertAdjacentHTML() invokes the HTML parser on a markup string and allows you to append HTML to a specified element.
Here's an example of using it to append HTML to a page, after document.body has been created, without using document.write:
// bodyAppend - append HTML string to body
function bodyAppend( htmlString) {
document.body.insertAdjacentHTML("beforeend", htmlString);
}
// and test
bodyAppend("<p style='color:green'>An appended paragraph</p>");
<h1>Page Header</h1>
Some existing page content.
'insertAdjacentHTML' can't be used in the head section of a page - document.body has not been created and is still set to null,
bodyAppend presented above is intended for beginners - it's just one example of a particular technique. Please read the linked documentation to understand the syntax used, and do a search for "how to modify the DOM in JavaScript" to learn more about the scope of the topic.

Using Chrome Developer Tab for realtime html and javascript testing

In Google chrome web browser
about:blank gives an empty page and F12 gives you access to Developer Tab.
Right-clicking a source in Elements gives Edit as Html Option in Developer Tab
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<button id="myBtn">Button</button>
</div>
<div id="demo">
</div>
<script>
document.getElementById("myBtn").addEventListener("click", function () {
document.getElementById("demo").innerHTML = "Hello World";
});
</script>
</body>
</html>
Above is a JavaScript snippet which I copied in. But JavaScript code is not executing. Is this work flow of real time html editing not supported in chrome ?
Your script would ran, if it existed there when the page gets loaded. After the page has loaded, no script tags will just run when edited in.
You could wrap everything inside the script tags into a function and call that I think, however.
One other, but kind of a useless and technical trick that might let you run JavaScript, by editing in elements after the page has loaded, looks something like this:
If you add that in to the loaded page's HTML, the script inside that input-element's onfocus-attribute should run. This, however, is no proper way to do anything other than Cross-Site Scripting (XSS).
You can use a template literal, document.write() at console. At about:blank page press F12, at console enter
var html = `<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<button id="myBtn">Button</button>
</div>
<div id="demo">
</div>
<script>
document.getElementById("myBtn").addEventListener("click", function () {
document.getElementById("demo").innerHTML = "Hello World";
});
</script>
</body>
</html>`;
document.write(html);
then click <button> element.
You can alternatively click Sources -> Snippets, type or paste the above javascript at center window, click right-pointing triangle at right panel to run javascript at Snippets. You can also right-click at Snippets panel to create a new snippet to run.

I want to do function at open Chrome with web site Javascript

I'm new at Javascript and I have a question.
I want to at start if I open Chrome and web site to do my function.
I want to every time do this function if I open Google Chrome!
I have adblock, and I want if every time I open this web site how2play.pl I want to delete this window scr.hu/0qbal/i9wa2 with code scr.hu/0qbal/gs9sy like in console paste document.getElementById('sdf09-8e9daf9e854f26f98cabf235ad8343cb').style.display = "none";
Please explain step by step.
<!doctype html>
<html>
<head>
<title>Testing</title>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
alertme('this works');
};
function alertme(text)
{
alert(text);
}
</script>
<button onclick="alertme('you clicked me');">Click Me</button>
</body>
</html>
When the page is done loading or if you click on the button, the code will run a javascript function that will display an alert box.
How it works
In the javascript there is a window.onload = function() -- which allows you to run any function you want immediately when the page is done loading (in this example it will run the alertme('this works');)
When you look at the button you will see that the button contains alertme('you clicked me');
That is also a function that executes when the button is clicked.

Adding JavaScript code with jQuery.html()

<!DOCTYPE HTML>
<html>
<head>
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var x="<script>alert('hello world');</script>";
$("#div_one").html(x);
});
</script>
</head>
<body>
<div id="div_one">
</div>
</body>
</html>
Why does this not work? I'd expect the JS code between the script tags to be interpreted and see an alert message ...
What I want to do:
I have written a set of functions that add and delete items from an array depending on the user input (JavaScript). Then, I have a function that draws() a ul-list of the items held in the array. Behind each item, I want to provide a remove link, which calls a JavaScript function that removes the item from the array and then calls drawList() to redraw the list.
If there weren't that security policy, I'd simply do it as in the code shown above.
That is some weird browser bug I believe. For some reason you can't have </script> inside the script block.
Change to
var x="<scr"+"ipt>alert('hello world');</scr"+"ipt>";
Example on jsFiddle
That is not a bug. The problem is here:
<script>
$(document).ready(function() {
var x="<script>alert('hello world');</script>";
$("#div_one").html(x);
});
</script>
The browser thinks the first <script> tag is associated with the </script> inside your code.
As you can see, the code is shown in the DOM instead of executing.
To further prove it, see this example:
http://jsfiddle.net/DerekL/Ah8Qz/
var x = $("<script>").html("alert('hello world');");
$("#div_one").append(x);
If you avoid the </script> closing tag, then there will be no problem because the HTML parser will ignore any open <script> tag inside <script>.
So to sum up,
Browsers does not have security in place to stop scripts being injected into your page.
This is no where near a browser bug.

Using jquery click event inside an editable div

I use JQuery to register events for different tags. Here is the code so far:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.7.js"></script>
</head>
<body>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<div><p>another one</p></div>
<p><strong>big one</strong></p>
<div contentEditable="true"><p>hello <b>there</b></p></div>
<script>
$("p").click(function () {
alert('p tag');
});
$("div").click(function () {
alert('div tag');
});
$("b").click(function () {
alert('strong tag');
});
</script>
</body>
</html>
I want to develop a simple text editor and want to capture click events so that I can update the state of my buttons (bold, italics, ...). I want the click events to work inside an editable div as well but they only fire once when the div tag is selected and afterwards when the editing begins, clicking anywhere inside that div doesn't fire, even though I have p and b tags inside the div. Is is possible to achieve this using an editable div? Basically I want to be able to know if the cursor is inside a b tag or an i tag so that I can update the state of my buttons.
you can use .one
$("editableDIV").one("click",function(){...});

Categories

Resources