Jquery syntax is usually made to select HTML elements and take action against selected element.
Syntax: $(selector). action()
Signs of dollars, to define jQuery (selector), to show the selected element or destination action (), is a jQuery action to be performed on the selected element.
[code language="ruby"] $ (this). hide() //hides the current element $ ("p"). hide() //hides all paragraphs or content of tag $ (". test"). hide() //hides elements that have the class = "test" $ ("# test"). show() //display the elements that have id = "test" [/code]
[code language="ruby"] $ ("p") <i>selects all elements $ ("p.intro") <i>select all elements that have <p> class = "intro". $ ("p # demo") <i><p> select elements that have id = "demo". [/code]
Similar in terms of XPath jQuery select elements based on existing attributes.
[code language="ruby"] $ ("[href]") select all elements with href attribute. <span style="font-family: Lato, 'Segoe UI', Frutiger, Tahoma, Helvetica, 'Helvetica Neue', Arial, sans-serif;"> $ ("[href = '#']") select all elements with href attribute value = "#". </span> [/code]
However, you should still try to optimize the way you retrieve elements. Not to mention that a lot of users still use older browsers that force jQuery into traversing the DOM tree, which is slow.
[code language="ruby"] $('li[data-selected="true"] a' ) // Fancy, but slow $('li.selected a' ) // Better $('#elem' ) // Best [/code]
Selecting by id is the fastest. If you need to select by class name, prefix it with a tag – $('li.selected'). These optimizations mainly affect older browsers and mobile devices.
How to handle multiple jQuery Objects Even worse is the process of repeatedly querying the DOM and creating multiple jQuery objects.
[code language="ruby"] $('#elem').hide(); $('#elem').html('bla'); $('#elem').otherStuff(); [/code]
Hopefully, you’re already aware of how inefficient this code is. If not, that’s okay; we’re all learning. The answer is to either implement chaining, or to “cache” the location of #elem.
[code language="ruby"] // This works better $('#elem') .hide() .html('bla') .otherStuff(); // Or this, if you prefer for some reason. var elem = $(' #elem'); elem.hide(); elem.html('bla'); elem.otherStuff(); [/code]