I have several polymer elements.
<ps-el-one/>
<ps-el-two/>
<ps-el-three/>
<ps-el-four/>
I want to be able to query all of the elements which begin with "ps-" with either a CSS selector or javaScript.
I whipped up the following solution, but I am wondering if there is anything more efficient?
var allElementsOnPage = document.querySelectorAll('*');
var res = [];
for (var index in allElementsOnPage) {
var el = allElementsOnPage[index];
if (el && el.tagName && el.tagName.substr(0, 3) == 'PS-') {
res.push(el);
}
}
This solution seems very inefficient.
This is not possible with CSS selectors.
The #id selector allows you to target an element by referencing the id HTML attribute. Similar to how class attributes are denoted in CSS with a “period” ( . ) before the class name, ID attributes are prefixed with an “octothorpe” ( # ), more commonly known as a “hash” or “pound sign”.
Class Selectors Match an element that has the specified class. To match a specific class attribute, we always start the selector with a period, to signify that we are looking for a class value. The period is followed by the class attribute value we want to match.
The CSS [Attribute ~= “value”] can select the element if it includes the word “value” in the attribute specified. For example, the following code looks for the value “shirt” in the attribute “title”. The above code selects the first two paragraphs since they have a shirt in their title, which is the target attribute.
The CSS class selector has a specific selector property to satisfy the use case requirement when the developer needs to select only a particular element rather than all with the same class. For example, I just want my “p” tag to be coloured red, but I have other elements too with the same class name and tag name defined.
All we did that’s different than the ends with ($=) selector is target the prefix by adding a ^ symbol in front of the = sign. You may also notice this time I used a class instead of an id. CSS is flexible enough to pretty much let you target anything as I stated earlier.
Selecting an element with CSS that has a repetitive suffix would look like this: The first thing to note is the div with the brackets surrounding the id$ attribute. The div tag can be any element in the DOM from input to span and so on. This is awesome if you’re trying to target a specific element that has a dynamic prefix like this:
Check this here
<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
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