lala

How do I clear inner HTML

I’ve been fiddling with this for a while but it won’t work and I can’t figure out why. Please help. Here is what I have:

    

lalala

function go(what) < document.getElementById("goy").innerHTML = what; >function clear()

The mouseover works and displays the text in the div, but when I move the mouse out of the h1 tag, the text stays there and I don’t know why, help would be appreciated.

4 Answers 4

The problem appears to be that the global symbol clear is already in use and your function doesn’t succeed in overriding it. If you change that name to something else (I used blah ), it works just fine:

    

lalala

function go(what) < document.getElementById("goy").innerHTML = what; >function blah()

This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.

A corollary to that is to not use old-style onxyz=. attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy

    

lalala

. and even better, use DOM2’s addEventListener (or attachEvent on IE8 and earlier) so you can have multiple handlers for an event on an element.

Источник

Javascript очистить содержимое элемента

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Clear the Content of a Div element using JavaScript

Use the replaceChildren() method to clear the content of a div element, e.g. div.replaceChildren() .

When the replaceChildren method is invoked without passing it any arguments, the method empties the element of all its children.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="container"> p>Applep> p>Pearp> p>Bananap> div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const container = document.getElementById('container'); container.replaceChildren();

We called the replaceChildren method without passing it any parameters, which cleared the contents of the div element.

The method can also be used to replace the existing children of an element with a provided set of children.

Copied!
const container = document.getElementById('container'); const p1 = document.createElement('p'); p1.innerHTML = `span style="background-color: lime">Applespan>`; const p2 = document.createElement('p'); p2.innerHTML = `span style="background-color: orange">Orangespan>`; container.replaceChildren(p1, p2); // ✅ If you have a collection of elements // use spread operator (. ) to unpack the collection // container.replaceChildren(. [p1, p2]);

By using the replaceChildren method, we can clear the contents of the div and add a new set of children to it in a single step, which is a bit faster.

The method takes one or more Node objects or strings, with which it replaces the element’s existing children.

# Clear the contents of a Div on a button click

Here is an example that clears the contents of a div element on a button click.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="container"> p>Applep> p>Pearp> p>Bananap> div> button id="btn">Clear div contentsbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const container = document.getElementById('container'); const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() container.replaceChildren(); >);

We added a click event listener to the button element.

Every time the button is clicked, the handleClick function is invoked, where we simply call the replaceChildren method.

# Empty a DOM element using textContent

Alternatively, you can set the element’s textContent property to an empty string.

Setting textContent on the element removes all of its children and replaces them with a single text node of the provided value.

Copied!
const container = document.getElementById('container'); container.textContent = '';

The textContent property can be used to read and set the text content of an element.

When using the property to set a node’s text content, all of the element’s children are removed and replaced with the provided string value.

You might also see the innerHTML property being used in a similar way.

Copied!
const container = document.getElementById('container'); container.innerHTML = '';

This achieves the same result, however, it might be slower because setting the innerHTML property uses the browser’s HTML parser.

The textContent property doesn’t use the browser’s HTML parser and might be faster if the element has many children.

Which approach you pick is a matter of personal preference. I’d go with the replaceChildren method as it is direct, easy to read and can be used to replace the removed child elements in a single step.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Remove all content using pure JS

I’m looking for a way to remove the entire content of a web page using pure Javascript — no libraries. I tried:

document.documentElement.innerHTML = "whatever"; 

but that doesn’t work: it replaces the inside of the element. I’m looking at replacing the entire document, including if possible the doctype and

To what end? Javascript works on the DOM which is a higher-level than the underlying HTML serialization (i.e. where the

I mourn the passing of the static web page, with the associated ability to look at the source code of any web page to understand how it was constructed and how it all works.

11 Answers 11

I think a browser rightfully assumes a page with content-type text/html will always be a web page — so whilst you may do something like.

It will still have some HTML hanging around.

document.documentElement.innerHTML = ''; 

Yi Jiang did suggest something clever.

window.location = 'about:blank'; 

This will take you to a blank page — an internal mechanism provided by most browsers I believe.

I think however the best solution is to use document.open() which will clear the screen.

The first updated answer was half of what I was looking for. But I guess changing the doctype is asking a bit too much.

@passcod Once you change the doctype too, you are changing how the browser will render your HTML/CSS. This will probably entail a page reload. I don’t think you can change a doctype on the fly.

@alex changing window.location to ‘about:blank’ has a problem with IE specialy IE10 because some addons when detect about:blank page fill it with their contents

var i = document.childNodes.length - 1; while (i >= 0)

Removes everything (doctype also) on FF 3.6, Chrome 3.195, and Safari 4.0. IE8 breaks since the child wants to remove its parent.

Revisiting a while later, could also be done like this:

Great, but you still can’t change the doctype. which doesn’t matter much. Firefox crashed when I tried.

According to Dotoro’s article on the document.clear method, they (since it’s deprecated) recommend calling document.open instead, which clears the page, since it starts a new stream.

This way, you avoid the nasty about:blank hack.

One can remove both the element ( document.documentElement ) and the doctype ( document.doctype ).

document.doctype.remove(); document.documentElement.remove(); 

Alternatively, a loop can be used to remove all children of the document .

while(document.firstChild) document.firstChild.remove(); 

After the page has already fully loaded:

document.write(''); document.close(); 

I believe this will do it

document.clear() //deprecated window.location = "about:blank" //this clears out everything 

That didn’t work for me, but I did try it on jsbin.com which may be doing something else behind the scenes.

@John Hartsock changing window.location to ‘about:blank’ has a problem with IE specialy IE10 because some addons when detect about:blank page fill it with their contents

Five years later, it is not so important that lots of things still don’t work in IE, since MS has stopped development of IE in favor of Edge.

I believe this will still leave the doctype node hanging around, but:

document.documentElement.innerHTML=''; document.open(); 

The Document.open() method opens a document for writing. if you dont use open method, you cant modify Document after set innerhtml to empty string

If youre using jQuery here’s your solution

 


If youre using javascript here’s your solution

 


var run = function()

Im just curious as to why you’d want to do that. Now theres no way that I know of to replace absolutely everything down to the doctype declaration but if you are wanting to go to those lengths why not redirect the user to a specially crafted page that has the template you need with the doctype you need and then fill out the content there?

EDIT: in response to comment, what you could do is strip all content then create an iframe make it fill the entire page, and then you have total control of the content. Be aware that this is a big hack and will probably be very painful — but it would work 🙂

To all who asked the reasons. This seemed like an easy way of stripping everything out and starting from scratch in a userscript. I can include whatever JS code I want, and it will run in the page, not in a sandbox. The doctype thing is for when I want to use xhtml on a html website.

@passcod — Changing the doctype is pointless. You wont end up with an XML document — only an HTTP content-type can do that. And if your building your DOM in javascript, you’re not going to validate it either.

REMOVE EVERYTHING BUT — !DOCTYPE html —

var l = document.childNodes.length; while (l > 1)

TESTED ON FIREFOX WEB INSPECTOR — childNodes[1] IS — !DOCTYPE html —

Источник

Читайте также:  Python обработать сообщение telegram bot
Оцените статью