Home > Article > Web Front-end > How to get tag content using JS
This time I will show you how to use JS to obtain tag content, and what are the precautions for using JS to obtain tag content. The following is a practical case, let’s take a look.
In our daily JS programming, we often need to obtain the content of tags and operate on them. There are many details that are easily overlooked by us. Now I will briefly summarize it based on the methods I usually use. If there are any errors, please correct them. The HTML structure is as follows:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p id="box"> <p>这有个 第一个p</p> <p>这有个第二个p</p> <span>这是个 span</span> <br> <a href="#">这有个a标签</a> </p> </body> </html>This method can get all the content in the tag, including tags, spaces, text, line breaks, etc.
Method 1, innerHTML
<script> var box = document.getElementById('box');// 获取标签的内容 var box1 = box.innerHTML; console.log(box1);</script>The JS code and renderings are as follows:
innerHTML gets the content in the tag
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 and content you want to set"; when setting the content, All original content will be overwritten. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
Detailed explanation of JS framework library use cases
The above is the detailed content of How to get tag content using JS. For more information, please follow other related articles on the PHP Chinese website!