Can i get all attributes that begin with "on" using jquery? - javascript

I am looking for a way to get all the attributes of an element that begins with "on" using jQuery or Vanilla JS. I am currently getting all attributes and then looping through them to get the ones I want using the method proposed by #primvdb on this post: Get all attributes of an element using jQuery.
My code looks like this:
/* Expanding .attr as proposed by #primvdb */
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
/* And then my function */
$.fn.attrThatBeginWith = function(begins){
var attributes = this.attr();
var attrThatBegin = {};
for(var attr in attributes){
if(attr.indexOf(begins)==0){
attrThatBegin[attr] = attributes[attr];
}
}
return attrThatBegin;
};
/* Usage */
var onAttributes = $("#MyElement").attrThatBeginWith("on");
And this works but is very "dirty". It's seems like with all the vast features of jQuery there should be a better "cleaner" way to do this. Does anybody have any suggestions?

You can get all attributes attached to an element with element.attributes.
The native attributes object can be converted to an array and then filtered based on the given string.
A plugin that does the above would look like
$.fn.attrThatBeginWith = function(begins){
return [].slice.call(this.get(0).attributes).filter(function(attr) {
return attr && attr.name && attr.name.indexOf(begins) === 0
});
};
FIDDLE

Related

Convert Javascript array back into JQuery-type object

For the code below, I wanted to make the _formsOk function work for both Javascript arrays and "JQuery objects". In function1(), I tried to create a Javascript array with all DOM elements except those that have a parent element with id="objectTypesContainer". Basically, function1() filters out the DOM elements I don't want before calling _formsOk() function, which does the actual form validation.
function1() {
var allForms = $('form:not(.vv_hidden)', this.selectMarketsContainer);
var nonObjectTypeForms = [];
allForms.each(function () {
if ($(this).parent().attr("id") !== "objectTypesContainer"){
nonObjectTypeForms.push($(this)[0]);
}
});
return this._formsOk(nonObjectTypeForms);
},
_formsOk: function($forms) {
var formOk = true;
console.log(typeof $forms)
$forms.each(function () { // This line fails
var validator = $(this).validate(DEFAULT_VALIDATION_OPTIONS);
if (!(validator && validator.form())) {
formOk = false;
}
});
return formOk;
},
However, I realized that because nonObjectTypeForms is now a JS Array rather than a "JQuery Object", the line marked (// This line fails) now fails.
The original code looked like this:
function1() {
var allForms = $('form:not(.vv_hidden)', this.selectMarketsContainer); // This is a "JQuery object", so no error occurs
return this._formsOk(allForms);
},
_formsOk: function($forms) {
var formOk = true;
console.log(typeof $forms)
$forms.each(function () { // This line fails
var validator = $(this).validate(DEFAULT_VALIDATION_OPTIONS);
if (!(validator && validator.form())) {
formOk = false;
}
});
return formOk;
},
Is there a way I can convert a JS array into a JQuery object ? I don't want to change _formsOk function definition just yet.
Instead of putting all elements in a new array, just use .filter() from the jQuery object.
allForms.filter(function () {
return $(this).parent().attr("id") !== "objectTypesContainer")
});
This will remove all the items you don't need in your selection and now allForms will only have the wanted elements.

Javascript inheritence in jquery way

If I set a function under an object i can use it once only like
function handle(selector)
{
return{
elem:selector,
next:function(){
return (this.nextSibling.nodeType==1) ? this.nextSibling : this.nextSibling.nextSibling;
}
}
}
here i can say handle.next() this will work but if I want to say handle.next().next().next() my question is how I can use in this way as jquery does?
Speaking about your function you can modify it like this to make it work:
function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
return{
elem:selector,
next:function(){
return handle(selector.nextElementSibling);
}
}
}
See jsfiddle.
UPD: Modified the code to support both elements and string selectors as a parameter.
UPD 2: Came out with an alternative variant. In this case we extend the native html element object and add new next method:
function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
selector.next = function() {
return handle(selector.nextElementSibling);
};
return selector;
}
Fiddle is here.

Array that can store only one type of object?

Is it possible to create an array that will only allow objects of a certain to be stored in it? Is there a method that adds an element to the array I can override?
Yes you can, just override the push array of the array (let's say all you want to store are numbers than do the following:
var myArr = [];
myArr.push = function(){
for(var arg of arguments) {
if(arg.constructor == Number) Array.prototype.push.call(this, arg);
}
}
Simply change Number to whatever constructor you want to match. Also I would probably add and else statement or something, to throw an error if that's what you want.
UPDATE:
Using Object.observe (currently only available in chrome):
var myArr = [];
Array.observe(myArr, function(changes) {
for(var change of changes) {
if(change.type == "update") {
if(myArr[change.name].constructor !== Number) myArr.splice(change.name, 1);
} else if(change.type == 'splice') {
if(change.addedCount > 0) {
if(myArr[change.index].constructor !== Number) myArr.splice(change.index, 1);
}
}
}
});
Now in ES6 there are proxies which you should be able to do the following:
var myArr = new Proxy([], {
set(obj, prop, value) {
if(value.constructor !== Number) {
obj.splice(prop, 1);
}
//I belive thats it, there's probably more to it, yet because I don't use firefox or IE Technical preview I can't really tell you.
}
});
Not directly. But you can hide the array in a closure and only provide your custom API to access it:
var myArray = (function() {
var array = [];
return {
set: function(index, value) {
/* Check if value is allowed */
array[index] = value;
},
get: function(index) {
return array[index];
}
};
})();
Use it like
myArray.set(123, 'abc');
myArray.get(123); // 'abc' (assuming it was allowed)

Method for getting jQuery element or value

I have set up a class that allows me to get an input/select element's value or the element itself:
My.Class = {
property: function(e){
var t = '#element_id';
return My.Helper.fetch(t, e);
}
}
My.Helper = {
fetch: function(t,e){
if (e == true) {
return jQuery(t);
};
return jQuery(t).val();
}
}
var element = My.Class.property(true);
var elementValue = My.Class.property();
This works great, but when I have dozens of properties, the code repeats quite a bit:
My.Class = {
property: function(e){
var t = '#element_id';
return My.Helper.fetch(t, e);
},
property_b: function(e){
var t = '#element_id_b';
return My.Helper.fetch(t, e);
},
property_c: function(e){
var t = '#element_id_c';
return My.Helper.fetch(t, e);
},
property_d: function(e){
var t = '#element_id_d';
return My.Helper.fetch(t, e);
}
}
How can I can I construct these properties without having to repeat myself so often? Keep in mind that my example property names and element names cannot always be consistent.
This seems like you should just have a get_property(selector_string) method that does this for you. The other alternative is that on instantiation the object could get a list of elements that you'd be able to 'reget' if the DOM's changed.

JavaScript - create element and set attributes

I've got these functions to create elements and change their attributes. Could you give me an advice on how to modify them?
function create(elem) {
return document.createElementNS ? document.createElementNS("http://www.w3.org/1999/ xhtml", elem) : document.createElement(elem);
}
function attr(elem, name, value) {
if (!name || name.constructor != String) return "";
name = {"for": "htmlFor", "class": "className"}[name] || name;
if (typeof value != "undefined") {
elem[name] = value;
if (elem.setAttribute) elem.setAttribute(name, value);
}
return elem[name] || elem.getAttribute(name) || "";
}
I want to get something like this create('div', {'id': 'test', 'class': 'smth'});
function create(elem, attr) {
if (!attr) return document.createElementNS ? document.createElementNS("http://www.w3.org/1999/xhtml", elem) : document.createElement(elem);
if (attr) {
var el = document.createElementNS ? document.createElementNS("http://www.w3.org/1999/xhtml", elem) : document.createElement(elem);
for (var i = 0; i < attr.length; i++) {
attr(el, name[i], value[i]);
}
return el;
}
}
Please help =]
You did pretty good but I have a solution for you that you should try that worked for me and it is quick and easier. It for the creating a element and sets attributes function.
as you mentioned:
I want to get something like this create('div', {'id': 'test', 'class': 'smth'});
here is the solution:
function create(ele, attrs) {
//create the element with a specified string:
var element = document.createElement(ele);
//create a for...in loop set attributes:
for (let val in attrs) {
//for support in the setAttrubute() method:
if (element.setAttribute) {
if (element[val] in element) {
element.setAttribute(val, attrs[val]);
} else {
element[val] = attrs[val];
}
} else {
element[val] = attrs[val];
}
}
//return the element with the set attributes:
return element;
}
This also works with custom attributes and it property's like innerHTML too.
If you also want to be sure that I know this works I have tested it and logged it on the console and seeing it on the HTML page. I tested this on Firefox.
Here's a Demo
You can't iterate through an object like that:
for (var k in attrs) {
if (attr.hasOwnProperty(k))
attr(el, k, attrs[k]);
}
Note that I changed your "attr" variable to "attrs" so that it doesn't hide the "attr" function you've created. Also, up in your "attr" function, change the "undefined" test:
if (typeof value !== undefined)
to be a little safer. Comparisons with "==" and "!=" attempt a type conversion, which is unnecessary if you're just checking undefined.
I would recommend a javascript framework like jQuery. They already have this functionality implemented.
$("<div/>", {
"class": "test",
text: "Click me!",
click: function(){
$(this).toggleClass("test");
}
}).appendTo("body");
A word of advice: I personally prefer the jquery way because you can add the css and events to the element directly, and refer to objects by a var name instead of the id, but... There are issues when using this method to create input elements, ie7 & ie8 don't allow you to set the type property so beware when creating a button, textbox, etc for example, jquery will throw a "type property can't be changed" error.
If the code is to be used in a browser before ie9, best use: document.createElement instead to increase compatibility.
export function Element(name, object = {}) {
const element = document.createElement(name);
for (const key in object) {
element[key] = object[key];
}
return element;
}
export function Anchor(object) {
return Element('a', object);
}
Use it like:
const anchor = Anchor({href: 'test'});

Categories