One of the most common features in many JavaScript libraries is the selection of DOM elements that match a pattern based on CSS selectors. Previously, because of the low understanding of JavaScript, the JavaScript-to-dom operation remained on getElementById () and getElementsByTagName, and the acquisition of classes had to forcibly encapsulate a function, such as
function Getelementbyclassname (tagname,classname) { var tags=document.getElementsByTagName ( TagName); var list=[]; for (var in tags) { var tag=tags[i]; if (tag.classname==className) {List.push (tag);} } return list;}
So in the actual development process is still more troublesome. The selector API that touches the DOM extension today feels like the door to a new world. The
Selector API is a standard specified by the Web launch, dedicated to allowing the browser to natively support CSS queries. The core approach is: Queryselector () and Queryselectorall (). It's easier to operate. The
Queryselector () method
Queryselector () method receives a CSS selector, returns the first element that matches the pattern, and returns null if no matching element is found. Take a look at the example below.
// Get BODY element var body = Document.queryselector ("body"); // get an element with id "text" var text = Document.queryselector ("#text"); // gets the element with the class name "selected" var selected = Document.queryselector (". Selected"); // get the first picture element of Class "button" var img = document.body.querySelector ("Img.button");
Queryselectorall () method
The Queryselecyorall () method receives a parameter like the Queryselector method, which is a CSS selector, but returns all matching elements instead of just one element. This method returns an NodeList instance, which is an array. Look at the following example.
Gets all the <p> elements in a div. var p = document.getElementById ("mydiv"). Queryselectall ("P");//Get all elements of Class "selected" var selecteds = Document.queryselectorall (". selected");
But because it is a form of an array, to manipulate each element in the array, you can use the item () method or the square bracket syntax such as:
var I, Len, selected; for (i=0;i<selecteds.len,i++) { = selecteds[i]; // or Selecteds.item (i); Selected.style.backgroundColor = "Red"; }
First essay, step by step, huh!
About JavaScript dom Extensions: Selector API