Getting method: 1. Use innerHTML attribute, syntax "body object.innerHTML"; 2. Use innerText attribute, syntax "body object.innerText"; 3. Use textContent attribute, syntax "body object.textContent" .
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use the innerHTML attribute
This method can get all the content in the tag, including tags, spaces, text, line breaks, etc.
If you want to clear the content of the tag, innerHTML = ""
; that's it
If you want to set the content of the tag, innerHTML = "Fill in the tag you want to set and content"; when setting content, all original content will be overwritten.
Code example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> div{ border: 2px dashed #006DAF; padding: 10px; width: 300px; } p{ border: 2px dashed #006DAF; padding: 10px; } </style> </head> <body id="body"> <div>div元素 <h2>一个标题</h2> <p>一个段落</p> </div><br /> </body> <script> var body = document.getElementById('body'); // 获取标签的内容 var body = body.innerHTML; console.log(body); </script> </html>
Rendering:
##Method 2: Use innerText attribute
This method gets all the text in the tag (and its sub-tags), but does not get the tag (or can filter out all tags). If there are multiple spaces or newlines, it will be parsed as one space. If you want to clear the content of the label, innerText = ""; that's itIf you want to set the content of the label, innerText = "Fill in the label and content you want to set"; set content, all original content will be overwritten. However, the tag will not be parsed and will be printed directly on the page as text. Code:<script> var body = document.getElementById('body'); // 获取标签的内容 var body = body.innerText; console.log(body); </script>
textContent to get the content in the tag. But textContent will retain the tag structure when filtering out tags.
Code example:
<script> var body = document.getElementById('body'); // 获取标签的内容 var body = body.textContent; console.log(body); </script>
Rendering:
##[Recommended learning: javascript advanced tutorial
】The above is the detailed content of How to get body content in Javascript. For more information, please follow other related articles on the PHP Chinese website!