Home > Article > Web Front-end > How to delete text in JavaScript
<p>Hello World</p><p>The code to delete the text node using JavaScript is as follows:
var node = document.getElementsByTagName("p")[0]; node.removeChild(node.firstChild);<p>This code first obtains the first one in the page
<p>
tag element, and then delete the first child node of the element, which is the text node "Hello World". It should be noted that if there are multiple text nodes in the element, they can all be deleted by looping through.
<p>
tag and the text nodes it contains in the following HTML code will be deleted together:
<div> <p>Hello World</p>
var node = document.getElementsByTagName("div")[0]; var childNode = node.getElementsByTagName("p")[0]; node.removeChild(childNode);<p>This code first obtains the
<div>
tag element, then obtains the first <p>
tag element in the element, and finally deletes it. Similarly, if there are multiple text nodes and sub-elements in the HTML element, you can delete them all by looping through them.
<input type="text" id="input-box"><p> To delete the content in the input box, you can use the following JavaScript code:
var inputBox = document.getElementById("input-box"); inputBox.value = "";<p> This code first obtains the input box element, and then Set its value attribute to an empty string, which deletes the content in the input box.
var selectBox = document.getElementById("select-box"); selectBox.removeChild(selectBox.options[index]);<p>This code first obtains the drop-down list element, and then calls its removeChild() method to delete the option at the specified position. Among them, the index parameter specifies the index value of the option to be deleted. For example, if you wish to remove the second option, you can set index to 1. <p>Summary <p>This article introduces the method of deleting text nodes, HTML elements, input box contents and drop-down list options in JavaScript. These operations are often used in the web development process. Mastering these techniques can make code work more efficient and flexible. Of course, you need to carefully check the relevant code before operation to avoid accidentally deleting other content and causing unnecessary trouble. Be sure to fully test the functionality of your code to ensure it works properly.
The above is the detailed content of How to delete text in JavaScript. For more information, please follow other related articles on the PHP Chinese website!