JQuery is a basic tutorial for manipulating various elements

  • 2020-03-30 03:48:38
  • OfStack

This article illustrates jQuery's operations on elements, including basic operations, choosing elements to manipulate, and working with DOM elements. It has a good reference value for the learning of jQuery. Share with you for your reference. Specific analysis is as follows:

1, the basic

Jquery object set:

$() : collection of jquery objects

Get the elements in the jquery object set:

Use the index to get the javascript elements in the wrapper:


var temp = $('img[alt]')[0]

Get the javascript elements in the jquery object set using jquery's get method:


var temp = $('img[alt]').get(0)

Using the eq method of jquery to get the jquery object elements in the jquery object set:

$(' img [Alt] '). Eq (0)
$(' img [Alt] '). The first ()
$(' img [Alt] '). The last ()

Jquery object set converted into javascript array:


var arr = $('label+button').toArray()

All the sibling button elements after the label are converted into a javascript array

Index of 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 the same as the previous line that cannot be found returns -1
Var n = $('img').index() gets the index of img in its sibling

Add more jquery object sets to jquery object sets:      
Use commas:


$('img[alt],img[title]')

Using the add method:


$('img[alt]').add('img[title]')

Take different approaches to different sets of jquery objects:


$('img[alt]').addClass('thickBorder').add('img[title]').addClass('');

Add a newly created element to the jquery object set:


$('p').add('<div></div>');

Delete an element in the jquery object set:


$('img[title]').not('[title*=pu]')
$('img').not(function(){return !$(this).hasClass('someClassname')})

Filter jquery object set:
$('td').filter(function(){return this.innerhtml.match (^\d+$)}) filters td containing Numbers

Gets a subset of the jquery object set

$('*').slice(0,4) contains a new set of jquery objects for the first four elements
Slice (4) contains a new set of jquery objects for the first four elements
$(' div ') from the (' img [Alt] ')

Convert the elements in the jquery object set:


var allIds = $('div').map(function(){
 return (this.id==undefined) ? null : this.id;
}).get();

The example above can be converted to a javascript array using the get method.

Traversing the elements in the jquery object set:


$('img').each(function(n){
 this.alt = ' This is the first ['+n+'] A picture. A picture id is ' + this.id;
})
$([1,2,3]).each(function(){alert(this);})

Get jquery object set using inter-element relations:

$(this). The closest (' div ') such as trigger button in which div
$(this).siblings('button[title="Close"]'
$(this).children('.someclassname') all child node elements, do not contain duplicate child nodes
$(this). The closest (' ') near the ancestor element
$(this).contents() a set of jquery objects made up of element contents, such as get < Iframe> Element content
$(this).next('. Someclassname ') next sibling
$(this).nextall ()
$(this).nextuntil ('.someclassname') all sibling elements until the target element is encountered
$(this).offsetparent () the parent element closest to the jquery object set
$(this).parent() direct parent element
$(this).parents() all parent elements
$(this).parrentsuntil () all parent elements up to the target parent
$(this).prev() the previous sibling
PrevAll () before $(this). PrevAll ()
$(this).prevtntl () before all sibling elements, up to the target element

Other ways to get jquery object sets:


$(this).find(p span)

Determine if it is a set of jquery objects:


var hasImg = $('*').is('img');

Jquery methods:

The $(). Hide ()
The $(). The addClass (' ')
The $(). The HTML (' ')
$('a').size() element number

Jquery selector:

$(" p: even)    
$(' child (1) the tr: NTH - ')
$(' body > Div ') direct child element
$('a[href=$=' PDF ']') is selected by attribute
$(div: from the (a)) filtering

Jquery functions:

$. The trim ()
Jquery execution time:
The $(document). Ready (function () {});
$(function () {});

Create DOM elements:


$('<p></p>').insertAfter();
$('<img>',{
 src: '',
 alt: '',
 title: '',
 click: function(){}
}).css({
 cursor:'pointer',
 border:'',
 padding:'',
 backgroundColor:'white'
}).append('');

Jquery extensions:


$.fn.disable = function(){
 return this.each(function(){
 if(this.disabled != null) this.disabled = true;
 })
};
$('').disable();

Jquery tests the existence of elements:

If (item)(){}else{} loose test
If (item! = null) recommended test to distinguish null from undefined

2. Select the element to operate on

By tag name: $('a')   
By id: $('#id')
By classname: $('.someclassname')
Satisfy multiple conditions: $('a#id.someclassname') or $('div,span')
All child nodes of an element: $(p.
Direct child of an element: $(ul.mylist > Li)
According to the property name:
$(a [href ^ = 'http://']) to... At the beginning
$(href = $' PDF ') to... At the end
$(form[method]) contains a form with the method attribute
$(intput [type = 'text'])
$(intput/name! = ' ')
$(href * = 'some')

The first element after an element: $(E+F) matches F, which is the first element after E

An element after an element: $(E~F) matches an F, which is an element after an E

Through position:

$(li:first) first li
$(li:last) last li
$(li:even) even line li
$(li:odd) odd line li
$(li:eq(n)) the NTH element, the index starts from 0
$(li:gt(n)) after the NTH element, the index starts at 0
$(li:lt(n)) before the NTH element, index from 0
The first li in the $(ul:first-child) list
The last li in the $(ul:last-child) list
The NTH li in the $(ul: NTH -child(n)) list
$(ul: limited-child) ul without brother li
$(ul:nth-child(even)) list of even lines li,odd for counting line li
Li in $(ul: NTH -child(5n+1)) list divided by 5 by 1

Through the filter:

$(input: not (: checkbox))
$(' : not (img/SRC * = "dog") ')
$(' img: not (/ SRC * = "dog") ')
$(div: from the (span))
$(' tr: from the (img/SRC $= "pu PNG") ')
$(tr:animated) tr in animated state
$(input:button) includes input of type button,reset, and submit
$(input:checkbox) = $(input[type=checkbox])
$(span:contains(food)) contains the word "food" within the span
$(input: disabled) are prohibited
$(input: enabled)
$(input:file) = $(input[type=file])
H1 to h6: $(header)
$(input: hidden)
$(input:image) = $(input[type=image])
$(:input) includes input, select, textarea, and button elements
$(tr: parent)
$(input:password) is the same as $(input[type=password])
$(input:radio) = $(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) = $(input[type=text])
$(div: visible)

Dealing with the DOM element & cake;  

Attributes of the operation element:


$('*').each(function(n){
 this.id = this.tagName + n;
})

Get the property value:


$('').attr('');

Set property value:


$('*').attr('title', function(index, previousValue){
 return previousValue + ' I am element ' + index + ' and my name is ' + this.id;
}) //Sets a value for a property
$('input').attr({
 value: '',
 title: ''
}); //Set values for multiple properties

Delete properties:


$('p').removeAttr('value');

Make all links open in a new window:


$('a[href^="http://"]').attr('target',"_blank");

Avoid multiple form submissions:


$("form").submit(function(){
 $(":submit", this).attr("disabled","disabled");
})

Add class name:


$('#id').addClass('')

Delete class name:


$('#id').removeClass('')

Switch class name:


$('#id').toggleClass('')

Delete the class name if it exists and add it if it does not
Determine whether the class name is included:


$('p:first').hasClass('') $('p:first').is('')

Returns the list of class names as an array:


$.fn.getClassNames = function(){
 var name = this.attr('someclsssname');
 if(name != null){
 return name.split(" ");
 }
 else
 {
 return [];
 }
}

Setting 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'
});

Size:

$(div). The width (500).
$(' div '). Height ()
$(' div '). InnerHeight ()
$(' div '). InnerWidth ()
$(' div '). OuterHeight (true)
$(' div '). OuterWidth (false)

Positioning:

$('p').offset() relative to the reference position of the document
$('p').position() offsets the relative position of the parent element
$('p').scrollleft () the offset of the horizontal scroll bar
$(" p "). ScrollLeft (value)
$(" p "). The scrollTop ()
$(" p "). The scrollTop (value)

About element content:

$(" p "). The HTML ()
$(" p "). The HTML (' ')
$(" p "). The text ()
$(" p "). The text (' ')

Additional content

Append a paragraph of HTML to the end of the element:


$('p').append('<b>some text</b>');

Existing elements in the dom at the end of the element:


$('p').append($(a.someclassname))

Append to the beginning of the element:


$("p").prepend()

Append to the element:


$("span").before()

Append to the element:


$("span")after()

Append the content to the end:


appendTo(targets)

Append the content to the beginning:


prependTo(targets)

Append the content to the element:


insertBefore(targets)

Append the content to the element:


$('<p></p>').insertAfter('p img');

Package elements:

$(' a.s omeclassname '). Wrap (" < Div class = 'hello' > < / div>" )
$(' a.s omeclassname '). Wrap ($(" div: first ") [0])
$(' a.s omeclassname '). WrapAll ()
$(' a.s omeclassname '). WrapInner ()
$(' a.s omeclassname '). UnWrap ()

Delete elements:

$('.classname').remove() removes the element, and the events and data bound to the element are also removed
$('.classname').detach() deletes elements but retains events and data
$('.classname').empty() does not delete elements, but empties their contents

Copy elements:


$('img').clone().appendTo('p.someclassname')

$('ul').clone().insertBefore('#id')

Replace elements:


$('img[alt]').each(function(){
 $(this).replaceWith('<span>' + $(this).attr('alt') + '</span>');
})
$("p").replaceAll("<b></b>")

Values for form elements:


$('[name="radioGroup"]:checked').val() Gets the value of the radio button and returns if none is selected undefined
var checkboxValues = $('[name="checkboxGroup"]:checked').map(function(){
 return $(this).val();
}).toArray(); //Gets the value of the multimarquee

For < Select id = "list" multiple = "multiple" > $('#list').val() returns an array of values
$('input').val(['one','two','three']) is selected if the menu or check box matches an element in the array

I believe that this article has a certain reference value for your jQuery programming.


Related articles: