JQuery fragment (1) Basics: select the elements to be operated, process DOM elements, and jquery Fragment
1. Basics
Jquery object set:
$ (): Jquery object set
Obtain the elements in the jquery object set:
Use the index to obtain the javascript element in the wrapper: var temp = $ ('img [alt] ') [0]
Use the get method of jquery to obtain the javascript element in the jquery object set: var temp = $ ('img [alt] '). get (0)
Use the jquery eq method to obtain jquery object elements in the jquery object set:
$('img[alt]').eq(0)
$('img[alt]').first()
$('img[alt]').last()
Convert a jquery object set to a javascript array:
Var arr = $ ('label + click'). toArray () label is followed by all button elements of the same level and converted to a javascript array.
Index of the jquery object set:
Var n = $ ('img '). index ($ ('img # id') [0]) Note: The index () parameter is a javascript element.
Var n = $ ('img '). index ('img # id') is equivalent to returning-1 if the previous row cannot be found.
Var n = $ ('img '). index () img index in the same level element
Add more jquery object sets to the jquery object set:
Use commas: $ ('img [alt], img [title] ')
Use the add method: $ ('img [alt] '). add ('img [title]')
Different methods are used for different jquery objects:
$('img[alt]').addClass('thickBorder').add('img[title]').addClass('');
Add new elements to the jquery object set:
$('p').add('<div></div>');
Delete the elements in the jquery object set:
$('img[title]').not('[title*=pu]')
$('img').not(function(){return !$(this).hasClass('someClassname')})
Filter jquery object sets:
$ ('Td '). filter (function () {return this. innerHTML. match (^ \ d + $)}) filter td containing numbers
Get a subset of jquery object sets
$ ('*'). Slice () contains the first four elements of the new jquery object set
$ ('*'). Slice (4) New jquery object set containing the first four elements
$('div').has('img[alt]')
Convert elements in a jquery object set
var allIds = $('div').map(function(){
return (this.id==undefined) ? null : this.id;
}). Get (); convert to a javascript Array Using the get Method
Traverse elements in a jquery object set
$('img').each(function(n){
This. alt = 'this is the ['+ n +'] image. The image id is '+ this. id;
})
$([1,2,3]).each(function(){alert(this);})
Get the jquery object set using the relationship between elements
$ (This). closest ('div '), for example, in which div the trigger button occurs
$ (This). siblings ('button [title = "Close"] ') All same-level elements, excluding
$ (This). children ('. someclassname') All child node elements, excluding repeated child nodes
$ (This). closest ('') near the ancestor Element
$ (This). contents () is a jquery object set composed of element content. For example, you can obtain the <iframe> element content.
$ (This). next ('. someclassname') next same level element
$ (This). nextAll () all peer Elements
$ (This). nextUntil ('. someclassname') all peer elements after the target Element
$ (This). offsetParent () parent element closest to the jquery object set
$ (This). parent () direct parent Element
$ (This). parents () All parent Elements
$ (This). parrentsUntil () All parent elements until the target parent Element
$ (This). prev () a sibling Element
All sibling elements before $ (this). prevAll ()
$ (This). All sibling elements before prevTntl () until the target Element
Other methods for getting jquery object sets
$(this).find(p span)
Determine whether a jquery object set is used
var hasImg = $('*').is('img');
Jquery method:
$().hide()
$().addClass('')
$().html('')
$ ('A'). size () element quantity
Jquery selector:
$('p:even')
$('tr:nth-child(1)')
$ ('Body> div ') direct sub-element
$ ('A [href =$ = 'pdf ']') Select
$ (Div: has (a) Filter
Jquery functions:
$.trim()
Jquery execution time:
$(document).ready(function(){});
$(function(){});
Create a DOM element:
$('<p></p>').insertAfter();
$('',{
src: '',
alt: '',
title: '',
click: function(){}
}).css({
cursor:'pointer',
border:'',
padding:'',
backgroundColor:'white'
}).append('');
Jquery extension:
$.fn.disable = function(){
return this.each(function(){
if(this.disabled != null) this.disabled = true;
})
};
$('').disable();
Check whether the jquery test element exists:
If (item) () {} else {} loose Test
If (item! = Null) Recommended test, can distinguish null from undefined
2. Select the elements to operate
Based on Tag Name: $ ('A ')
Based on id: $ ('# id ')
Based on the class name: $ ('. someclassname ')
Meet multiple conditions: $ ('a # id. someclassname') or $ ('div, span ')
All subnodes of an element: $ (p a. someclassname)
Direct subnode of an element: $ (ul. myList> li)
Based on the property name:
$ (A [href ^ = 'HTTP: // ']) starts...
Ended...
$ (Form [method]) form containing the method attribute
$(intput[type='text'])
$(intput[name!=''])
$ (Href * = 'some') contains
The first element after an element: $ (E + F) matches F, and F is the first element after E.
An element after an element: $ (E ~ F) matches F, and F is an element after E.
Location:
$ (Li: first) The first li
$ (Li: last) The last li
$ (Li: even) an even number of rows li
$ (Li: odd) odd line li
$ (Li: eq (n) indicates the nth element. The index starts from 0.
$ (Li: gt (n) the element after the nth element. The index starts from 0.
$ (Li: lt (n) indicates the element before the nth element. The index starts from 0.
$ (Ul: first-child) The first li in the list
$ (Ul: last-child) The last li in the list
$ (Ul: nth-child (n) the nth li in the list
$ (Ul: only-child) ul without brother li
$ (Ul: nth-child (even) indicates the even number of rows in the list. The odd indicates the counting row li.
$ (Ul: nth-child (5n + 1) li in the list divided by 5
Filter:
$(input:not(:checkbox))
$(':not(img[src*="dog"])')
$('img:not([src*="dog"])')
$(div:has(span))
$('tr:has(img[src$="pu.png"])')
$ (Tr: animated) tr in the animation state
$ (Input: button) includes the Input values of the type buttons, reset, and submit.
$ (Input: checkbox) is equivalent to $ (input [type = checkbox])
$ (Span: contains (food) span containing text food
$ (Input: disabled) disabled
$ (Input: enabled) enabled
$ (Input: file) is equivalent to $ (input [type = file]).
$ (: Header) h1 to h6
$(input:hidden)
$ (Input: image) is equivalent to $ (input [type = image])
$ (: Input) includes input, select, textarea, And button elements.
$(tr:parent)
$ (Input: password) is equivalent to $ (input [type = password])
$ (Input: radio) is equivalent to $ (input [type = radio])
$ (Input: reset) is equivalent to $ (input [type = reset]) or $ (button [type = reset])
$('.clssname:selected')
$ (Input: submit) is equivalent to $ (input [type = submit]) or $ (button [type = submit])
$ (Input: text) is equivalent to $ (input [type = text])
$(div:visible)
3. Process DOM elements
Operation element attributes:
$('*').each(function(n){
this.id = this.tagName + n;
})
Get the property value: $ (''). attr ('');
Set the property value:
$('*').attr('title', function(index, previousValue){
return previousValue + ' I am element ' + index + ' and my name is ' + this.id;
}) Set a value for a property.
$('input').attr({
value: '',
title: ''
}); Set values for multiple attributes
Delete attributes:
$('p').removeAttr('value');
Open all links in a new window:
$('a[href^="http://"]').attr('target',"_blank");
Avoid multiple forms:
$("form").submit(function(){
$(":submit", this).attr("disabled","disabled");
})
Add Class Name: $ ('# id'). addClass ('')
Delete Class Name: $ ('# id'). removeClass ('')
Switch Class Name: $ ('# id'). If toggleClass ('') exists, the class name will be deleted. If it does not exist, the class name will be added.
Determine whether the class name is included: $ ('P: first '). hasClass ('') $ ('P: first'). is ('')
Returns the list of class names in array format:
$.fn.getClassNames = function(){
var name = this.attr('someclsssname');
if(name != null){
return name.split(" ");
}
else
{
return [];
}
}
Set style:
$('div.someclassname').css(function(index, currentWidth){
return currentWidth + 20;
});
$('div').css({
cursor: 'pointer',
border: '1px solid black',
padding: '12px 12px 20px 20x',
bacgroundColor: 'White'
});
Dimension:
$(div).width(500)
$('div').height()
$('div').innerHeight()
$('div').innerWidth()
$('div').outerHeight(true)
$('div').outerWidth(false)
Positioning:
$ ('P'). offset () relative to reference position of the document
$ ('P'). position () offset relative position of the parent Element
$ ('P'). scrollLeft () offset value of the horizontal scroll bar
$('p').scrollLeft(value)
$('p').scrollTop()
$('p').scrollTop(value)
Related element content:
$('p').html()
$('p').html('')
$('p').text()
$('p').text('')
Append content
Append an html: $ ('P'). append ('<B> some text </B>') at the end of the element ');
Existing dom elements at the end of the element: $ ('P'). append ($ (a. someclassname ))
Append at the beginning of the element: $ ("p"). prepend ()
Append an element before: $ ("span"). before ()
Append the following element: $ ("span") after ()
Append the content to the end: appendTo (targets)
Append content to the beginning: prependTo (targets)
Append the content to the front of the element: insertBefore (targets)
Append the content to the end of the element: $ ('<p> </p>'). insertAfter ('P img ');
Package elements:
$('a.someclassname').wrap("<div class='hello'></div>")
$('a.someclassname').wrap($("div:first")[0])
$('a.someclassname').wrapAll()
$('a.someclassname').wrapInner()
$('a.someclassname').unWrap()
Delete element:
$ ('. Classname'). remove () deletes an element. Events and data bound to the element are also deleted.
$ ('. Classname'). detach () deletes elements, but retains events and Data
$ ('. Classname'). empty () does not delete the element, but clears the element content.
Copy element:
$('img').clone().appendTo('p.someclassname')
$('ul').clone().insertBefore('#id')
Replacement element:
$('img[alt]').each(function(){
$(this).replaceWith('<span>' + $(this).attr('alt') + '</span>');
})
$("p").replaceAll("<b></b>")
Values of form elements:
$ ('[Name = "radioGroup"]: checked'). val () gets the value of the single-choice button. If no one is selected, undefined is returned.
var checkboxValues = $('[name="checkboxGroup"]:checked').map(function(){
return $(this).val();
}). ToArray (); get the value of the multiple selection box
For <select id = "list" multiple = "multiple"> arrays returned by using $ ('# list'). val ()
$ ('Input'). val (['one', 'two', 'three ']) if the single sequence or check box matches the element in the array, select the status.
References: jQuery practice (version 2)
Why does jquery operate on dom elements?
You have written the document as doclument.
In addition, document. getElementById () is not jquery, but native javascript. The returned Dom object does not use the show () method.
How to operate HTML elements using jQuery
JQuery Selector
The jQuery element selector and attribute selector allow you to select HTML elements by Tag Name, attribute name, or content.
The selector allows you to operate on HTML element groups or individual elements.
In html dom terminology:
The selector allows you to operate a DOM element group or a single DOM node.
Selector instance Selection
* $ ("*") All elements
# Id $ ("# lastname") id = "lastname" element
. Class $ (". intro") All class = "intro" Elements
Element $ ("p") All <p> Elements
. Class. class $ (". intro. demo") All class = "intro" and class = "demo" Elements
: First $ ("p: first") first <p> element
: Last $ ("p: last") last <p> element
: Even $ ("tr: even") All even <tr> Elements
: Odd $ ("tr: odd") All odd <tr> Elements
: Eq (index) $ ("ul li: eq (3)") The fourth element in the list (index starts from 0)
: Gt (no) $ ("ul li: gt (3)") list elements with an index greater than 3
: Lt (no) $ ("ul li: lt (3)") list elements whose index is less than 3
: Not (selector) $ ("input: not (: empty)") All input elements not empty
: Header $ (": header") All title elements : All animation elements of animated
: Contains (text) $ (": contains ('w3school')") contains all elements of the specified string
: Empty $ (": empty") all elements of nodes without child (element)
: Hidden $ ("p: hidden") All hidden <p> Elements
: Visible $ ("table: visible") all visible tables
S1, s2, s3 $ ("th, td,. intro") All elements with matching Selection
[Attribute] $ ("[href]") All elements with the href attribute
[Attribute = value] $ ("[href = '#']") the value of all href attributes is equal to the element "#".
[Attribute! = Value] $ ("[href! = '#'] ") The value of all href attributes is not equal to" # & quot ...... the remaining full text>