Abstract
In many cases, we need to get HTML elements. This post will introduce: How to use JQury to get elements by id, class, tagname, xpath?
Keywords: HTML , element , JQuery , id , class , tagname , xpath.
Import JQuery
When using JQuery to get HTML elements, you need to import the JQuery package firstly. If you do not want to download and save JQuery, you can use CDN to import. After import, we can get element by id, class, tagname and Xpath.
// CDN import JQuery
// The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking.
// This allows browsers to ensure that resources hosted on third-party servers have not been tampered with.
// Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source.
// Read more at srihash.org
Id Class TagName
In JQuery, you can get elements by Id Class TagName and mixing of them. Note that the object returned by JQuery selector is an array.
// by tag id
$("#demo") //get id="demo"
// by tagname
$("p") //get all
// by class
$("intro") //get all elements which class="intro"
// mix use of id、class、tagname
$("p.intro") // get all
elements which class="intro"
$("p#demo") // get all
elements which id="demo"
// get all elements in that class="example"
$("div .example a")
$("div.example a")
Xpath
Using XPath in JQuery to select elements with a given attribute.
$("[href]") // get all elements have "href" ttrattibute
$("[href='#']") // get all elements which href="#"
$("[href!='#']") // get all elements which href!="#"
$("[href$='.png']") // get all elements which href endwith ".png"
Summarize
When we need to get elements, we can use the powerful JQuery. After importing JQuery through CDN, we can easily get elements by id, class, tagname and Xpath. If you don’t like JQuery, you can also use original Javascript to get elements. For more details, please read the related articles.
Related articles
Coming soon
If yuo have any question or need any help
you can leave a comment or connect me with weichaoxu1998@gmail.com