2. DOM Selectors #
Created Saturday 11 July 2020
Element Selectors #
To get the element object(call it eObj)
- We can select elements and attributes in the DOM(document object) using functions called DOM selectors. The most common ones are:
getElementsByTagName('arg')
- returns a list of element objects with the ‘arg’ tag. e.g all<p>
, all sgetElementsByClassName('arg')
- returns a list of element objects with class ‘arg’.getElementById('arg')
- returns the element object with ‘arg’ as id. singular(no s)
- If we need one or all element objects like CSS selector - they are much powerful and preferred over getElements:
document.querySelector('selector')
- returns the first element which matches the ‘selector’.document.querySelectorAll('selector')
- returns the list of all elements which match the ‘selector’.
Note:
- Elements can be searched inside any node, not just
document
. Thus, doingeObj.querySelector('')
is allowed and will search insideeObj
.
Attribute Selectors #
Assuming we’ve got the eObj, and now want the attributes
- For editing/reading attributes:
elementObj.getAttribute('attribute');
//prints the attribute value
elementObj.setAttribute('attribute', 'newvalue');
// change the attribute
- We can access and change inline style attributes directly by doing
elementObj.style.backgroundColor = 'red'
. But it is discouraged as it violates the principle of separation of concerns.
is equivalent to Note: .style won’t be able to acesss external CSS.
- Because an element can have multiple classes, we have special properties for it:
eObj.className = 'newname';
if there’s only one class- `eObj.classList; returns a read only list of classnames. It has 3 useful functions
eObj.classList.add('new_class');
eObj.classList.remove('remove_class');
eObj.classList.toggle('class name');
toggles the presence of a class.
Content Selectors - Change content in the tag or input #
eObj.innerHTML = 'New content';
ignores unused tags,<code></code>
is invisible. Susceptible to scripting attackseObj.textContent = 'New verbatim text';
<code></code>
will appear verbatim here.eObj.value;
// for input tags like text, file etc
Relative selectors #
eObj.parentElement
- the parent elementeObj.children
- a list of the children elementseObj.firstElementChild
eObj.nextElementSibling
andeObj.previousElementSibling
eObj.contains(eObj2)
- check if nodeeObj
containseObj2