Just jQuery The Core UI - The DOM |
Written by Ian Elliot | ||||
Thursday, 05 May 2022 | ||||
Page 3 of 3
Selectors in JavaScriptWe have seen how selectors are used in CSS, but how do we use them in JavaScript? The answer is that every DOM node object has a set of functions that will find objects based on selectors. The key functions are:
There is also a function that will find object based on any valid CSS selector:
So for example if you have: <button id="button1">My Button</button> then you can write things like var button=document.getElementById(“button1”); Notice that this can only return a single object, but the other two functions return a collection of elements that match the selector. You could also use: var button=document.querySelectorAll(“#button1”); Notice that, as far as programming is concerned, giving an HTML element an id is very like giving a UI component a name in other languages; so much so that most browsers will create a JavaScript global variable with the same name as the id that references the DOM object that represents the element. So, for example, you can ignore getElementById and use: var w= button1.offsetWidth; That is, button1 is a reference to the DOM object that represents the button. This might seem a simplification, but it is something that is implemented by the browser and it cannot be relied upon in the future. It is much better to write code that does not use these global variables and using getElementById is just as easy and using jQuery is even easier. In book but not included in this extract
SummaryIn this chapter we have looked at how JavaScript and the DOM work together and how jQuery makes this easier. This is just an initial overview and we will find out more about jQuery and the way it lets you work with the DOM in later chapters. What you should take from this chapter is:
Available as a Book:
buy from Amazon
Also Available:buy from Amazon To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info <ASIN:1871962501> <ASIN:1871962528> <ASIN:1871962560> <ASIN:1871962579> |
||||
Last Updated ( Friday, 27 May 2022 ) |