search
HomeWeb Front-endJS TutorialDetailed explanation of HTML element operations with JavaScript examples

This article brings you relevant knowledge about javascript, which mainly introduces issues related to the operation of html elements, including how to obtain the operated elements, the content of the operated elements, and the Properties, styles, etc., I hope it will be helpful to everyone.

Detailed explanation of HTML element operations with JavaScript examples

Related recommendations: javascript tutorial

1. Get the elements of the operation

Methods and properties of the document object

The document object provides some methods for finding elements. These methods can be used to obtain the operated element based on the element's id, name, class attributes and tag name.

Detailed explanation of HTML element operations with JavaScript examples

Summary

Except the document.getElementById() method returns the element with the specified id, all other methods return is a collection that meets the requirements. To get one of the objects, you can get it by subscript, which starts from 0 by default.

The document object provides some properties that can be used to obtain elements in the document. For example, get all form tags, image tags, etc.

Detailed explanation of HTML element operations with JavaScript examples

Detailed explanation of HTML element operations with JavaScript examples

  • The body attribute of the document object is used to return the body element.
  • The documentElement property of the document object is used to return the root node html element of the HTML document.

Note

The operation elements obtained through the methods of the document object and the properties of the document object represent the same object. For example, document.getElementsByTagName(‘body’)[0] is identical to document.body.

Detailed explanation of HTML element operations with JavaScript examples

HTML5’s new document object method

In HTML5, the element that is more convenient for obtaining operations is the document object. Two new methods have been added, namely querySelector() and querySelectorAll().

  • querySelector() method is used to return a reference to the first object in the document that matches the specified element or CSS selector.
  • querySelectorAll() method is used to return a collection of objects in the document that match the specified element or CSS selector.

Since these two methods are used in the same way, the following uses the document.querySelector() method as an example.

Methods and properties of the Element object

In DOM operations, the element object also provides methods for obtaining specified elements within an element. The two commonly used methods are getElementsByClassName( ) and getElementsByTagName(). They are used in the same way as the methods of the same name on the document object.

Detailed explanation of HTML element operations with JavaScript examples

#In addition, the element object also provides the children attribute to obtain the child elements of the specified element. For example, get the child elements of ul in the above example.

Detailed explanation of HTML element operations with JavaScript examples

  • #The children attribute of the element object also returns a collection of objects. If you want to get one of the objects, you also need to get it by subscripting, starting from 0 by default.
  • In addition, the document object also has the children attribute, and its first child element is usually an html element.

HTMLCollection object

  • HTMLCollection object: return by calling the getElementsByClassName() method, getElementsByTagName() method, children attribute, etc. through the document object or Element object set of objects.
  • NodeList object: When the document object calls the getElementsByName() method, the NodeList object is returned in Chrome and FireFox browsers, and the HTMLCollection object is returned in IE11.

The difference between HTMLCollection and NodeList objects:

  • HTMLCollection object is used for element operations.
  • NodeList object is used for node operations.

Tip: For the collection returned by the getElementsByClassName() method, getElementsByTagName() method and the children attribute, the id and name can be automatically converted into an attribute.

Detailed explanation of HTML element operations with JavaScript examples

2. Element content

In JavaScript, if you want to operate on the obtained element content, you can use the DOM provided Property and method implementation.

Detailed explanation of HTML element operations with JavaScript examples

  • The properties belong to the Element object and the methods belong to the document object.
  • innerHTML will maintain the written format and tag style when used.
  • innerText is plain text content with all formatting and tags removed.
  • The textContent attribute will retain the text format after removing the tag.

For example

Detailed explanation of HTML element operations with JavaScript examples

##Code implementation

	nbsp;html>
	
	
	<meta>
	<title>元素内容操作</title>
	
	
	<p>
	The first paragraph...
	</p><p>
	The second paragraph...
	<a>third</a>
	</p>
	
	<script>
	var box = document.getElementById(&#39;box&#39;);
	console.log(box.innerHTML);
	console.log(box.innerText);
	console.log(box.textContent);
	</script>
	
	

Note

The innerText attribute may cause browser compatibility issues when used. Therefore, it is recommended to use innerHTML to get or set the text content of elements as much as possible during development. At the same time, there are certain differences between the innerHTML attribute and the document.write() method in setting content. The former acts on the specified element, while the latter reconstructs the entire HTML document page. Therefore, readers should choose the appropriate implementation method according to actual needs during development

[Case] ​​Changing the box size

Detailed explanation of HTML element operations with JavaScript examplesCode implementation ideas

:

① Write HTML and set the size of p.

② Change the box size based on the number of user clicks.

③ When the number of clicks is an odd number, the boxes become larger, and when the number of clicks is an even number, the boxes become smaller.

Code implementation

	nbsp;html>
	
	
	<meta>
	<style>
	.box{width:50px;height:50px;background:#eee;margin:0 auto;}
	</style>
	
	
	<p></p>
	<script>
	var box = document.getElementById(&#39;box&#39;);
	var i = 0; // 保存用户单击盒子的次数
	box.onclick = function() { // 处理盒子的单击事件
	++i;
	if (i % 2) { // 单击次数为奇数,变大
	this.style.width = &#39;200px&#39;;
	this.style.height = &#39;200px&#39;;
	this.innerHTML = &#39;大&#39;;
	} else { // 单击次数为偶数,变小
	this.style.width = &#39;50px&#39;;
	this.style.height = &#39;50px&#39;;
	this.innerHTML = &#39;小&#39;;
	}
	};
	</script>
	
	
3. Element attributes

Use the attributes attribute to get all the attributes of an HTML element, as well as the length of all attributes. Detailed explanation of HTML element operations with JavaScript examples


For example

##Code implementationDetailed explanation of HTML element operations with JavaScript examples

	nbsp;html>
	
	
	<meta>
	<title>元素属性操作</title>
	<style>
	.gray{background: #CCC;}
	#thick{font-weight: bolder;}
	</style>
	
	
	<p>test word.</p>
	<script>
	// 获取p元素
	var ele = document.getElementsByTagName(&#39;p&#39;)[0];
	// ① 输出当前ele的属性个数
	console.log(&#39;未操作前属性个数:&#39; + ele.attributes.length);
	// ② 为ele添加属性,并查看属性个数
	ele.setAttribute(&#39;align&#39;, &#39;center&#39;);
	ele.setAttribute(&#39;title&#39;, &#39;测试文字&#39;);
	ele.setAttribute(&#39;class&#39;, &#39;gray&#39;);
	ele.setAttribute(&#39;id&#39;, &#39;thick&#39;);
	ele.setAttribute(&#39;style&#39;, &#39;font-size:24px;border:1px solid green;&#39;);
	console.log(&#39;添加属性后的属性个数:&#39; + ele.attributes.length);
	// ③ 获取ele的style属性值
	console.log(&#39;获取style属性值:&#39; + ele.getAttribute(&#39;style&#39;));
	// ④ 删除ele的style属性,并查看剩余属性情况
	ele.removeAttribute(&#39;style&#39;);
	console.log(&#39;查看所有属性:&#39;);
	for (var i = 0; i < ele.attributes.length; ++i) {
	console.log(ele.attributes[i]);
	}
	</script>
	
	

4. Element style

Review: Modify the style through the operation of element attributes.

Element style syntax: style.Attribute name.

Requirements: The horizontal dash "-" in the CSS style name needs to be removed, and the second English initial letter must be capitalized.

Example: The background-color that sets the background color needs to be changed to backgroundColor in the style attribute operation.

Detailed explanation of HTML element operations with JavaScript examples

NoteDetailed explanation of HTML element operations with JavaScript examples

The float style in CSS conflicts with the reserved words of JavaScript. Different browsers have different solutions. For example, IE9-11, Chrome, and FireFox can use "float" and "cssFloat", Safari browser uses "float", and IE6~8 use "styleFloat".

Question: An element can have multiple class selectors. How to operate the selector list during development?

Original solution: Use the className attribute of the element object to obtain the result. The obtained result is a character type, and then process the string according to the actual situation. The method provided by HTML5: the class selector list of the new classList (read-only) element.

Example: If the class value of a p element is "box header navlist title", how to delete the header?

HTML5 solution: p element object.classList.toggle("header");

For example

Code implementationDetailed explanation of HTML element operations with JavaScript examples

	nbsp;html>
	
	
	<meta>
	<title>classList的使用</title>
	<style>
	.bg{background:#ccc;}
	.strong{font-size:24px;color:red;}
	.smooth{height:30px;width:120px;border-radius:10px;}
	</style>
	
	
	
  • PHP
  • JavaScript
  • C++
  • Java
<script> // 获取第2个li元素 var ele = document.getElementsByTagName(&#39;li&#39;)[1]; // 若li元素中没有strong类,则添加 if (!ele.classList.contains(&#39;strong&#39;)) { ele.classList.add(&#39;strong&#39;); } // 若li元素中没有smooth类,则添加;若有删除 ele.classList.toggle(&#39;smooth&#39;); console.log(&#39;添加与切换样式后:&#39;); console.log(ele); </script> <script> ele.classList.remove(&#39;bg&#39;); console.log(&#39;删除后:&#39;); console.log(ele); </script>

In addition, the classList attribute also provides many other related operation methods and properties.

5. [Case] ​​Tab bar switching effectDetailed explanation of HTML element operations with JavaScript examples

Detailed explanation of HTML element operations with JavaScript examples##Code implementation ideas
:

① Write HTML to realize the structure and style design of the tab bar, where class equals current to indicate the currently displayed tab, and the default is the a label.

  • ② Get all tags and the display content corresponding to the tags.

  • ③ Traverse and add a mouse-over event for each label. In the event handler, traverse all the display content corresponding to the label. When the mouse slides over the label, pass the classList The add() method adds current, otherwise it is removed through the remove() method.


  • Code

	nbsp;html>
	
	
	<meta>
	<title>标签栏切换效果</title>
	<style>
	.tab-box{width:383px;margin:10px;border:1px solid #ccc;border-top:2px solid #206F96;}
	.tab-head{height:31px;}
	.tab-head-p{width:95px;height:30px;float:left;border-bottom:1px solid #ccc;border-right:1px solid #ccc;background:#206F96;line-height:30px;text-align:center;cursor:pointer;color:#fff;}
	.tab-head .current{background:#fff;border-bottom:1px solid #fff;color:#000;}
	.tab-head-r{border-right:0;}
	.tab-body-p{display:none;margin:20px 10px;}
	.tab-body .current{display:block;}
	</style>
	
	
	<p>
	</p><p>
	</p><p>标签一</p>
	<p>标签二</p>
	<p>标签三</p>
	<p>标签四</p>
	
	<!--jkdjfk?-->
	<p>
	</p><p> 1 </p>
	<p> 2 </p>
	<p> 3 </p>
	<p> 4 </p>
	
	
	<script>
	// 获取标签栏的所有标签元素对象
	var tabs = document.getElementsByClassName(&#39;tab-head-p&#39;);
	// 获取标签栏的所有内容对象
	var ps = document.getElementsByClassName(&#39;tab-body-p&#39;);
	for (var i = 0; i < tabs.length; ++i) { // 遍历标签部分的元素对象
	tabs[i].onmouseover = function() { // 为标签元素对象添加鼠标滑过事件
	for (var i = 0; i < ps.length; ++i) { // 遍历标签栏的内容元素对象
	if (tabs[i] == this) { // 显示当前鼠标滑过的li元素
	ps[i].classList.add(&#39;current&#39;);
	tabs[i].classList.add(&#39;current&#39;);
	} else { // 隐藏其他li元素
	ps[i].classList.remove(&#39;current&#39;);
	tabs[i].classList.remove(&#39;current&#39;);
	}
	}
	};
	}
	</script>
	
	

相关推荐:javascript教程

The above is the detailed content of Detailed explanation of HTML element operations with JavaScript examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)