Selectors
Selecting by ID:
$('#foo')
document.getElementById('foo')
Selecting by class (not compatible with IE6-8, but good with everything else):
$('.bar')
document.getElementsByClassName('bar')
Selecting by tag name:
$('span')
document.getElementsByTagName('span')
Selecting sub-elements:
$('#foo span')
document.getElementById('foo').getElementsByTagName('span')
Selecting "special" elements:
$('html')
document.documentElement
$('head')
document.head
$('body')
document.body
Attributes
Getting/setting HTML:
$('#foo').html()
document.getElementById('foo').innerHTML
$('#foo').html('Hello, world!')
document.getElementById('foo').innerHTML = 'Hello, world!'
Dealing with classes:
$('#foo').addClass('bar')
document.getElementById('foo').className += ' bar '
$('#foo').removeClass('bar')
document.getElementById('foo').className = document.getElementById('foo').className.replace(/bar/gi, '')
$('#foo').hasClass('bar')
document.getElementById('foo').className.indexOf('bar') !== -1
Getting an input's value:
$('#foo').val()
document.getElementById('foo').value
Effects
Showing and hiding:
$('#foo').show()
document.getElementById('foo').style.display = ''
$('#foo').hide()
document.getElementById('foo').style.display = 'none'
Changing CSS:
$('#foo').css('background-color', 'red')
document.getElementById('foo').style.backgroundColor = 'red'
Events
Document ready
Do it the way MDN does it:
document.onreadystatechange = function() {
if (document.readyState === 'complete') {
// DOM is ready!
}
};
Second, use domReady, a tiny library that's used like this:
domready(function() {
// DOM is ready!
});
Clicks
$('#foo').click(function() { ... })
document.getElementById('foo').onclick = function() { ... }
Parsing JSON:
jQuery.parseJSON(json)
JSON.parse(json)
// The JSON object isn't in older browsers, so you can include it if it's not there.
// http://github.com/douglascrockford/JSON-js/blob/master/json2.js
Комментариев нет:
Отправить комментарий