the document.querySelector() can selects the attributes also? - javascript

I recently saw a code voucher that surprised me a bit and I would really like to understand. Can the document.querySelector() take a parameter, an attribute to make selections :
const tabs = document.querySelectorAll('[data-tab-value]')
<span data-tab-value="#tab_1">Tab-1</span>
I would also like to know why the attribute name is enclosed in brackets.

document.querySelector is just like CSS selectors
It can even select elements with attributes like:
document.querySelector("input[name]") // <input name>; input which has attribute name
document.querySelector("input[type=number]") // <input type='number'>; input whose attribute type's value is number

Related

Protractor - checkbox with dynamic id cannot be defined

I need to define a specific check box and (later on) click on it to complete the account creation. The problem is that part of the input id is dynamic and changes with each run. Therefore, my approach below is not working:
var nativeChannels = element(by.css("label[for='dp-native-9597']"));
When I inspect the element, it displays the following:
div class="switch"input id="dp-native-9597" type="checkbox" ng-model="controls.allNativeChannels" class="cmn-toggle cmn-toggle-round ng-pristine ng-untouched ng-valid" autocomplete="off">label for="dp-native-9597">/label/div
label for="dp-native-9597"/label
I searched for a way to put a wild character after dp-native- but looks like this is not allowed. Is there any way to define this type of check box, so that I could move on with tests?
Thank you for your help in advance!
Try using the below xpath.
.//label [contains(#for,"dp-native-")]
There are wild card selectors in CSS (http://www.w3schools.com/cssref/css_selectors.asp) :
[attribute^=value] a[href^="https"] Selects every <a> element whose href attribute value begins with "https"
[attribute$=value] a[href$=".pdf"] Selects every <a> element whose href attribute value ends with ".pdf"
[attribute*=value] a[href*="w3schools"] Selects every <a> element whose href attribute value contains the substring "w3schools"
Try one of these. I think you might search like this:
$(".switch[id*='dp-native'] label")
or by model (http://www.protractortest.org/#/api?view=ProtractorBy.prototype.model) :
element(by.model('controls.allNativeChannels')).$('label');

How to match id in javascript for dynamically added field on html?

In our rails app, dynamic fields can be added to the form. Here is a html source code for the dynamically added field order_order_items_attributes_1413563163040_unit_price:
<div class="input decimal required order_order_items_unit_price">
<label class="decimal required control-label" for="order_order_items_attributes_1413563163040_unit_price">
<abbr title="required">*</abbr>
Unit Price($)
</label>
<input id="order_order_items_attributes_1413563163040_unit_price" class="numeric decimal required span5 span5" type="number" step="any" name="order[order_items_attributes][1413563163040][unit_price]">
</div>
As you can see, there is 13 digits string in field's id and it is randomly generated when the field is added. How we can match (locate) this type of random id in javascript? rails app uses jquery (ex, $('#order_order_items_attributes_xxxxxxxxxxxxx_unit_price').change(function (){})).
We are new to this css type of id match. More detail would be appreciated.
You have to first decide what algorithm you're using for matching the id values. Based on your comments (it is not specified precistly in your question), it appears you want to find all ids that start with "order_order_items_attributes_" and end with "_unit_price" and have a sequence of digits between them.
You can do that like this by find all the ids that start with the thing you want and then filtering them to things that only match all three criteria:
// find ids that match this pattern: order_order_items_attributes_xxxxxxxxxxxxx_unit_price
var orderItemRegex = /^order_supplier_id_\d+_unit_price$/;
$("[id^='order_supplier_id_']").filter(function(index) {
return orderItemRegex.test(this.id);
}).change(function() {
// this will be only the ids that match
});
This uses jQuery to make a list of all objects that have an id that starts with "order_supplier_id_". It then filters through that list eliminating any objects who don't match the full regex /^order_supplier_id_\d+_unit_price$/ that defines your pattern and then hooks up the .change() event handler to only the objects that pass the regex test.
Have you tried
$("input").prop("id");
That'll search for your input field and find the id property.
Use the for attribute of your <label>:
var selector = $('.decimal.required.control-label').eq(0).attr('for'),
element = $('#'+selector);
console.log(element);
// [<input id="order_order_items_attributes_1413563163040_unit_price" ... >]
You can use an attribute selector to match an id that "contains" the specified value, using [attr*=value]. Like:
$("[id*='order_supplier_id']").change(function() {
});
MDN's docs on attribute selectors specifies the kinds of selectors you can use to match the attribute, among them:
[attr*=value]
Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.
You could maintain an array of element IDs that gets updated each time the form element is added. Then call your change method on the elements in your array. But that isn't necessary if the change event callback is identical for all the new elements. Just call it on the class.

How to get elements of similar name? jQuery

<input name="Indian_Karnataka_Bangalore" value="Bangalore" />
<input name="Indian_Andhra_Hyderabad" value="Hyderabad" />
<input name="Indian_Kerala_Trivandrum" value="Trivandrum" />
<input name="Indian_Maharashtra_Mumbai" value="Mumbai" />
At a given time, only one input element will be present in the DOM. How will I know the name of the specific input element name? I don't want to depend on values as it might change.
Using jQuery.
The INDIAN term will be static in every input element.
Actually i am trying to validate the input elements. DOM will have all the elements but at a given time only one element will be active and that element should have some value in it.
var $inputs = $('input[name*="Indian"]'),
inputsName = $inputs.attr('name');
You can use the same selectors as you would CSS.
Chris Coyier wrote a piece on attribute selectors here
var indianInputs = $("input[name^='Indian']");
//Matches all input elements whose name attrributes 'begin' with 'Indian'
This differs than the one posted by #ahren in that his selector will match all input elements whose name attribute contain the string 'Indian'.
indianInputs.attr("name");
Would return the first matched element's name attribute's value, which, for your markup will be Indian_Karnataka_Bangalore
To find the names of all indianInputs, you must iterate over all matched elements
var indianInputNames = [];
indianInputs.each(function() {
indianInputNames.push($(this).attr("name"));
});
$('input[name="element_name"]')
You have a lot of ways to select by the name of the attribute check http://api.jquery.com/category/selectors/attribute-selectors/
Try
var name = $('input[name^="Indian_"]').attr('name')
Have you tried the filter function? Something like this:
$('input:visible')
.filter(function() {
return $(this).attr("name").match(/^Indian/);
});
This will return an array of input elements whose name starts with "Indian".
There is a good example here: https://stackoverflow.com/a/193787/1237117.

jquery hasClass, can it be given the beginning of class name, to get the full class name

I'm trying to do something similar to this question, but it's a bit different, so the solution there isn't working for me.
<span class="a-class another-class test-top-left"></span>
I have an element (this code shows a span but it could be div span or anything). This element has a class beginning with test- (test-top-left, test-top-right etc.) I've triggered a click event on classes starting with test- and saved the clicked object as var object = this;. Simple stuff so far.
What I'm trying to do now is get the full name of that class (test-top-left). I know it starts with test- but what's the full name. The thing is that there are other classes a-class another-class and test-top-left. Can hasClass be used to get the full name of the class? I'd prefer not to use find() or filter() just because there may be additional elements within that also have class="test-"
Edit:
The code I have now is, but it gives me ALL the classes. What I need is the single class beginning with test-.
var object = this;
$(object).attr('class');
So now I for loop through all the classes and test each one separately, which seems like a lot of unnecessary code. I'm hoping jQuery has a clever way to get the exact class that was clicked right away.
Description
You can use jQuerys Attribute Contains Selector, .attr() and .click() method.
Attribute Contains Selector - Selects elements that have the specified attribute with a value containing the a given substring.
.attr() - Get the value of an attribute for the first element in the set of matched elements.
.click() - Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
Sample
html
<span class="anyclass test-hello">Hello World</span>​
jQuery
$("[class*='test']").click(function() {
var object = $(this);
alert(object.attr("class").match(/(test-.*?)(?:\s+|$)/)[1])
;});
Check out the updated jsFiddle
Update
If you dont want to use regex you can do this.
$("[class*='test']").click(function() {
var object = $(this);
alert("test-" + object.attr("class").split("test-")[1].split("-"))
;});
​
More Information
jQuery - Attribute Contains Selector
jQuery - .attr()
jQuery - .click()
jsFiddle Demonstration
This should work for you:
var object = this;
var className = object.className.match(/(test-.*?)(?:\s+|$)/)[1];
Class name is the name of the class you are looking for.
If you don't want to use split or regex, you can try having the class in a separate attribute
<span class="someclass test-something" _rel="test-something">test<span>
or
<span class="someclass" _rel="test-something">test<span>
with the script
$("[_rel*='test-']").click(....
And to retrieve the attribute, use $(this).attr("_rel")

How to access HTML of a Input element

Hi I am trying to get the HTML of INPUT tag. But unable to..
<input type="checkbox" name="_QS4_CNA" id="_Q0_C7" class="mrMultiple" value="NA">
<label for="_Q0_C7">
<span class="mrMultipleText" style="">None of these</span>
</label>
</input>
And I am trying access as
var dat=$(':checkbox#_Q0_C7').html();
alert(dat);
But i cannot access this. Please help me on this..
The ".html()" method gets the contents of an element, and not the element itself. In your case, the problem is that your HTML is invalid. An <input> tag cannot have content. As far as the browser is concerned, the tag ends where the <label> tag starts, and the browser just ignores the closing tag.
Note that when you've got an "id" attribute to use to find an element, you don't need any other qualifiers in the selector (like ":checkbox"). Just "#_Q0_C7" is all you need, because "id" values have to be unique anyway.
edit — Note that if all you want is to get some attribute (like the value or the "checked" status) from the element, you can certainly do that:
var $cb = $('#_Q0_C7');
var isChecked = !!$cb.prop('checked'); // force a real boolean value
var value = $cb.val();
You can try accessing the RAW underlying DOM element and use its innerHTML property.
var dat = $(":checkbox#_Q0_C7")[0].innerHTML;
But like mentioned by Pointy, that might still get you nothing. Not sure what (if any) input elements have actual siblings.

Categories

Resources