Home >Web Front-end >JS Tutorial >Introduction to the basic usage of jQuery tag elements
Introduction to the basic usage of jQuery tag elements
With the continuous development of front-end development technology, jQuery, as an excellent JavaScript library, is widely used in web development. Among them, the label element is one of the important components in jQuery. This article will introduce the basic usage of jQuery tag elements, and attach specific code examples.
1. Introduction of jQuery library
To use jQuery, you first need to introduce the jQuery library into the HTML page. It can be imported through a CDN link or the jQuery library file can be downloaded locally.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
2. Basic usage
Selector
In jQuery, you can select elements on the page through selectors in order to operate on them.
// 通过标签名选择元素 $('p') // 通过类名选择元素 $('.class-name') // 通过id选择元素 $('#id-name')
Getting and setting HTML content
You can use the .text() method to get and set the text content of the label element, and use the .html() method to get and set the HTML of the label element. content.
// 获取文本内容 $('p').text() // 设置文本内容 $('p').text('新的文本内容') // 获取HTML内容 $('div').html() // 设置HTML内容 $('div').html('<p>新的段落</p>')
Add and delete elements
You can use the .append() method to add new child elements to the label element, and the .remove() method to delete the label element.
// 添加子元素 $('ul').append('<li>新的列表项</li>') // 删除元素 $('p').remove()
Hide and show elements
You can use the .hide() method to hide the label element and the .show() method to display the label element.
// 隐藏元素 $('img').hide() // 显示元素 $('img').show()
Add and remove class names
You can use the .addClass() method to add a class name to a label element, and the .removeClass() method to remove a class name.
// 添加类名 $('div').addClass('new-class') // 移除类名 $('div').removeClass('old-class')
Event handling
You can use the .on() method to bind event handling functions to label elements.
// 点击事件 $('button').on('click', function(){ alert('按钮被点击了') })
The above is an introduction to the basic usage of jQuery tag elements. Select elements through selectors, obtain setting content, add and delete elements, hide and display elements, add and remove class names, and event handling, etc. Operation can achieve rich and colorful interactive effects. I hope this article can help readers better understand and use the tag element function in the jQuery library.
The above is the detailed content of Introduction to the basic usage of jQuery tag elements. For more information, please follow other related articles on the PHP Chinese website!