html中两种获取标签内的值的方法
There are two primary methods for retrieving the value of an element's content in HTML:
1. Using the innerText
property:
The innerText
property directly accesses the text content of an element, including any nested elements and whitespace. It returns a string representation of the element's inner text.
Syntax:
JavaScript
element.innerText;
Example:
HTML
<p>This is a paragraph with some text.</p>
JavaScript
const paragraphElement = document.querySelector('p');
const paragraphText = paragraphElement.innerText;
console.log(paragraphText); // Output: This is a paragraph with some text.
2. Using the textContent
property:
The textContent
property is similar to innerText
but handles text content more consistently across different browsers. It treats non-visible characters like tabs and newlines as spaces and ignores <script>
and <style>
elements.
Syntax:
JavaScript
element.textContent;
Example:
HTML
<p>This is a paragraph with some text. </p>
JavaScript
const paragraphElement = document.querySelector('p');
const paragraphText = paragraphElement.textContent;
console.log(paragraphText); // Output: This is a paragraph with some text.
Choosing between innerText
and textContent
:
Use innerText
when you specifically need to access the raw text content, including whitespace and potentially hidden elements.
Use textContent
for more consistent and reliable text retrieval across different browsers, especially when dealing with non-visible characters or script/style elements.
Additional Considerations:
Both methods return a string representation of the element's content, not the actual DOM content.
To modify the content of an element, you can use the innerHTML
property, which directly sets the HTML code within the element.
For input fields, the value
property is used to retrieve or set the input value.