While trying to manipulate the layout of external sites I am often forced to use a chain of selectors to target the specific element I want. The first time I encountered this I was offered a jQuery solution and it is very easy to get results. I would prefer not to rely on jQuery and would like to know how feasible this is in standard Javascript. Here is an example jQuery 'chain' -
$('div[id="entry"] > p[class="header"] > span[id="title"] > div[class*="entry"] > p[class="title"] > a[class*="target"]').. etc
So say the HTML structure is roughly
<div id="entry">
<p class="primary">
<p class="header">
<span class="side">
<span id="title">
<div class="secondary entry">
<p class="return">
<p class="title">
<a class="img">
<a class="mytargetelement">
So how is this possible normally? Thanks.
In CSS, selectors are patterns used to select the element(s) you want to style, but as you can tell from the title above, selectors are also useful in javascript and below are some examples on how to use them.
JS uses the CSS syntax to select and manipulate HTML elements. Selectors are used to "find" (select) HTML elements based on their tag name, id, classes, types, attributes, values of attributes and much more. A list of all selectors can be found in our CSS Selector Reference.
DOM Selectors is used to selecting HTML elements within a document using JavaScript. There are two types of a selector, i.e., single element selector and multiple element selector.
DOM Selectors, as the name suggests is used to select HTML elements within a document using JavaScript. There are 5 ways in which you can select elements in a DOM using selectors. getElementsByTagName() getElementsByClassName() getElementById()
Enter document.querySelectorAll.
It's what jQuery uses internally for browsers that support it. The syntax is the same as in jQuery (Sizzle) selectors, see Selectors API.
This isn't pretty..
For each nested/chained element you can get its children via childNodes property. And then let the looping commence. :/ You'd then have to recursively loop through all children and children's children, and so on, until you find the appropriately matched element(s).
Updated:
To check for part of class name, you can do something like this:
if (element.className.indexOf('myClass') >= 0) {
// found it!
}
If you want to avoid jQuery and only use complex CSS selectors then the SizzleJS library might be what you need. It's a lot easier than doing it yourself every time you're looking for a DOM element!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With