Home > Web Front-end > JS Tutorial > body text

How to get tag content using JS

php中世界最好的语言
Release: 2018-06-04 18:00:01
Original
3042 people have browsed it

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>
Copy after login

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(&#39;box&#39;);//    获取标签的内容
     var box1 = box.innerHTML;
     console.log(box1);</script>
Copy after login

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:

How to use filter globally

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template