官术网_书友最值得收藏!

Traversal and manipulation

We discussed various methods of element selection using jQuery. We will discuss several DOM traversal and manipulation methods using jQuery in this section. These tasks would be rather tedious to achieve using native DOM manipulation. jQuery makes them intuitive and elegant.

Before we delve into these methods, let's familiarize ourselves with a bit of HTML terminology that we will be using from now on. Consider the following HTML:

<ul> <-This is the parent of both 'li' and ancestor of everything in 
  <li> <-The first (li) is a child of the (ul)
    <span>  <-this is the descendent of the 'ul'
      <i>Hello</i>
    </span>
  </li>
  <li>World</li> <-both 'li' are siblings
</ul>

Using jQuery traversal methods, we select the first element and traverse through the DOM in relation to this element. As we traverse the DOM, we alter the original selection and we are either replacing the original selection with the new one or we are modifying the original selection.

For example, you can filter an existing selection to include only elements that match a certain criterion. Consider this example:

var list = $( 'li' ); //select all list elements
// filter items that has a class 'highlight' associated
var highlighted = list.filter( '.highlight );
// filter items that doesn't have class 'highlight' associated 
var not_highlighted = list.not( '.highlight );

jQuery allows you to add and remove classes to elements. If you want to toggle class values for elements, you can use the toggleClass() method:

$( '#usename' ).addClass( 'hidden' );
$( '#usename' ).removeClass( 'hidden' );
$( '#usename' ).toggleClass( 'hidden' );

Most often, you may want to alter the value of elements. You can use the val() method to alter the form of element values. For example, the following line alters the value of all the text type inputs in the form:

$( 'input[type="text"]' ).val( 'Enter usename:' );

To modify element attributes, you can use the attr() method as follows:

$('a').attr( 'title', 'Click' );

jQuery has an incredible depth of functionality when it comes to DOM manipulation—the scope of this module restricts a detailed discussion of all the possibilities.

主站蜘蛛池模板: 汝南县| 高邮市| 福建省| 库尔勒市| 定州市| 虎林市| 黄梅县| 中江县| 西城区| 宁夏| 大英县| 通辽市| 曲阳县| 盐源县| 鲜城| 合阳县| 万山特区| 怀化市| 黄浦区| 奇台县| 湖州市| 镇坪县| 福州市| 当阳市| 阿拉尔市| 文安县| 中牟县| 武山县| 水富县| 清新县| 紫阳县| 林芝县| 武功县| 东兰县| 麻栗坡县| 嘉荫县| 长子县| 五河县| 泰州市| 辉南县| 海兴县|