JQuery: Custom Attribute Keyword Selector - javascript

For a project I'm using a custom attribute on elements to designate whether or not they'll have a custom template. I need the ability to select elements with a custom template based on a keyword. I've made a simplified case for demonstration.
So, for example:
<div jk_template="blue">Blue</div>
<div jk_template="red">Red</div>
<div jk_template="red big">Red Big</div>
I've tried:
$('[jk_template="blue"]').css('color', 'blue');
$('[jk_template="red"]').css('color', 'red');
$('[jk_template="red big"]').css('font-size','22px');
Unfortunately the red big only appears with larger font-size, but not colored red.
Fiddle
I also want to be able to select elements that don't have the custom template based on the absence of the attribute. Is all of this possible using just JQuery selectors?

Yes and JQuery actually leverages CSS 1-3 selectors.
To select an element with a specific attribute value substring use [attr*=value]:
$('[jk_template*="red"]').css('color', 'red');
To select an element without a specific attribute use the :not selector:
$(':not([jk_template])').css('color','orange');
Updated Fiddle

Related

How to select element with single class name in Jquery?

I have below html and want to get the element based on 'natural' class. The reason is I get t dynamic classes after 'natural'
<coral-checkbox class="natural coral-Form-field coral3-Checkbox" ></coral-checkbox>
I am trying below code to get hide the element but it is not working.
$("coral-checkbox[class='.natural']").hide();
But it is working when I select entire class like below but I need to do with only 'natural'. Is this possible ?
$("coral-checkbox[class='.natural coral-Form-field coral3-Checkbox']").hide();
Use .classname to select based on any of the element's classed. When you use an attribute selector, it matches the entire attribute (unless you use modifiers like *=, but they're not appropriate here, either).
$("coral-checkbox.natural").hide();
Use the class the selector instead of the attribute selector:
$("coral-checkbox.natural").hide();

Get dropdown option element by display text

I've currently been selecting dropdown elements by using:
$('#dropdownId option[value="value"]')
because most of my elements have been written as
<option value="value">value</option>
However, now I've come across some elements in this project that do not have the value attribute and instead look like
<option>value</option>
Now I'm struggling to select it using the same syntax that I used prior. I'd like to get the element (not just change the selection) using the same style as before, because it's a format that's used dynamically throughout the project. I've tried these so far:
$('#dropdownId option[value="value"]'); // doesn't work, I'd assume because it doesn't have a value attribute
$('#dropdownId option[text="value"]'); // Doesn't work, I'd assume because "text" isn't actually an attribute
$('#dropdownId option[label="value"]'); // Doesn't work, I'd assume because even though the value is used as the display text, it's not actually specified in the attributes.
I can't add a value="value" to the object, I don't have control over the html.
Edit: I realize that WebdriverIO, while it uses selectors similar to jQuery, doesn't necessarily have all of the same functionality. Nathan Hinchey's seems to work for normal jQuery though.
Stolen whole cloth from this answer:
You can use the jQuery contains selector
$('option:contains("value")')
You could dynamically alter the HTML by adding a value attribute to option elements that don't have one and use the .text() of the option as the .value. Then, you could continue to select options as you already are. There are performance cost to altering the DOM (perhaps extensively) so beware of that.
// Get all the <option> elements that don't have a "value" attribute and iterate the group
$("option:not([value])").each(function(){
// Create the "value" attribute for the option and give it the value of the
// current option element's text.
$(this).attr("value", $(this).text());
});
console.log($("select").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
</select>
Nathan Hinchey's answer works for people using base jQuery.
For people who are using WebDriverIO, I found this discussion which uses the selector
$('<element>*=<text>').
So, for my example, I used
$('option*=value')
However, I noticed that I couldn't nicely chain various selects in the single select, such as
$('select#selectId option*=value') // WON'T work
If you need to chain any selections prior to it, such as maybe the select object containing the options, instead use
$('option*=value').$(elementSelector)
I'm currently using this to get the parent object, the object.
$('option*=value').$('..')

How to iterate through all html elements of the same type but apply different changes to each one?

My code contains div tags nested within a single div tag. Each of these nested tags has two attributes, one is "number" and the other is "type". At one point in my code, I need to go over all of these div elements, select only those which have type="guessed" and change their text to the value of their respective "number" attribute.
More specifically:
$('div div[type="guessed"]').text(???);
I can't figure out what to type in place of the question marks.
Use the anonymous function available to text():
$('div div[type="guessed"]').text(function(){
return this.getAttribute('number');
/* Or, to use more jQuery:
return $(this).attr('number');
*/
});
Note, though, that neither type nor number are valid attributes of the <div> element.
As noted in the comments if you wish to add custom attributes to an element it's better – under HTML 5 – to use the data-* attributes, which will validate under the HTML 5 doctype (<!doctype html>). Using non-prefixed attributes will work, but they are, however, invalid (under both HTML 4.x and 5).
References:
data-* custom attributes.
text().
Something like this perhaps
$('div div[type="guessed"]').text($(this).attr('number'));

jQuery selector custom attribute

I have elements in my page like
<div class="editableTxt" data-model-attr="name" data-model-id="123">some text</div>
Now how do I write a selector in jQuery based on the 2 custom attribute values.
So i want something like select element with data-model-attr="name" data-model-id="123"
I want to get a unique element. So I use the 2 attributes.
USe like this
$("[data-model-attr='name'][data-model-id='123']")
As you specified element and not div, have you simply tried:
$('[data-model-attr="name"][data-model-id="123"]');
JSFiddle: http://jsfiddle.net/TrueBlueAussie/x23BV/
for a div obviously just add div:
$('div[data-model-attr="name"][data-model-id="123"]');
Use:
$('div[data-model-attr="name"][data-model-id="123"]');
$('div[data-model-attr="name"][data-model-id="123"]')
But don't use it, it's very slow, set id or classes to this div.

Selecting a CSS element by attribute(s) [plural!]

I've been using CSS3 selectors to select specific elements based on their attributes, although today, I have programmed myself into a corner, where I need a select a specific element based on the presence of TWO different attributes, instead of only 1.
e.g. I need to select the first div.
<div data-foo="bar" data-bar="baz">
<div data-foo="bar" data-bar="lorem">
<div data-foo="ipsum" data-bar="baz">
Just for fun, I tried div[data-foo="bar", data-bar="baz"], but not surprisingly, that didn't work.
Is there any way for me to get that specific element?
Right now, the only solution I can think of is to select all elements with the correct data-foo attribute, and then loop through the results to find the element with the correct data-bar attribute.
You were close, it's:
div[data-foo="bar"][data-bar="baz"]
Live example
From the CSS 2.1 specification:
Here, the selector matches all SPAN elements whose "hello" attribute has exactly the value "Cleveland" and whose "goodbye" attribute has exactly the value "Columbus":
span[hello="Cleveland"][goodbye="Columbus"] { color: blue; }
(There's a new CSS3 Selectors spec as well, which is increasingly supported, but we don't need CSS3 features for this.)

Categories

Resources