I'm using Zepto.js, a lightweight jquery clone. But that framework doesn't use .data() in the same way as jquery. Now I need to use this code:
var position = new Array;
$('#ipadmenu > section').each(function() {
position.push($(this).data('order'));
});
But I have no idea how to make this work on my framework.
How would I convert this to pure javascript? I have never really worked with arrays so i'm quite lost... also, might I have skipped something in the zepto doc (https://github.com/madrobby/zepto) that could help me with this? .get() for example?
Here is the HTML code. Basically I want to add all sections (the amount can change) into the array:
<nav id="ipadmenu">
<section data-order="0">
<a><p>text</p></a>
</section>
<section data-order="1">
<a><p>text</p></a>
</section>
</nav>
thank you for your help!
Based on my 30 second review of the zepto docs, it would look like this.
var position = new Array;
$('#ipadmenu > section').each(function() {
position.push($(this).data('order'));
});
the zepto docs you linked to say it supports all of the jquery methods in your snippet.
What about the data doesn't it handle? If it really doesn't handle data the same it also supports attr so you could say:
var position = new Array;
$('#ipadmenu > section').each(function() {
position.push($(this).attr('data-order'));
});
Here an alternative "pure" javascript solution:
var position = [];
var aSections = document.getElementById('ipadmenu').childNodes;
for (iIndex in aSections) {
if (aSections[iIndex].nodeName == 'SECTION') {
position.push(aSections[iIndex].getAttribute('data-order'));
}
}
Also see my jsfiddle.
=== UPDATE ===
A little smaler solution:
var position = [];
var aSections = document.getElementById('ipadmenu').getElementsByTagName('SECTION');
for (i = 0; i < aSections.length; i++) {
position.push(aSections[i].getAttribute('data-order'));
}
Here the new jsfiddle.
If you are using the data-* attributes then you can access them through the new dataset object available in HTMLElement. dataset is a StringMap object so you access the values using camel cased attribute names as the keys. If dataset is not available (if browser isn't HTML5 compatible or dataset spec is not implemented in the browser) then you can access the attribute using the regular attribute retrieval method.
So, if you have:
<script type="text/javascript">
var dataSet = document.getElementById("input1").dataset;
for(var key in dataSet) {
console.log("attribute is: " + key);
console.log(dataSet[key]);
}
</script>
<input type="text" id="input1" data-custom-attribute="some value"/>
Zepto support $(elem).data("attr-name") method, when you use a Custom Build of Zepto with "data" module. So, you can use same code for jquery and Zepto
Related
If you were to label elements by some [tag] system, likely attached by the user, and you wanted to count the number of tags (defined by the number of classes the element has), how would you accomplish this?
This could be beneficial if you were to try to review all elements by number of tags. (This likely could be accomplished by other structures, but if you were to only reference the element tags in this way)
Jquery has .hasClass(), is there something like .classCount()
You could create it...
$.fn.classCount = function() {
return $.grep(this.attr("class").split(/\s+/), $.trim).length;
};
jsFiddle.
If you don't have jQuery, you could use...
var classLength = element.classList.length;
jsFiddle.
If you don't have jQuery and have to support the older browsers, go with...
var classes = element.className.replace(/^\s+|\s+$/g, "").split(/\s+/);
var classLength = classes[0].length ? classes.length : 0;
jsFiddle.
You can use the classList attribute if you are using HTML5. For example
$("#someElementId").classList.length
would return 2 for:
<div id="someElementId" class="stinky cheese"></div>
as in http://jsfiddle.net/thegreatmichael/rpdEr/
$(element).attr('class').split(/\s+/).length
jsFiddle example
I have the following in javascript:
var entriesString = '';
$$('select[id=shopId]').each(function(elem, i){
shops[i] = elem.value;
entries[i] = new Array();
$$('input[id=entry'+i+']').each(function(elem, c){
if(elem.value != '') entries[i][c] = elem.value.replace(".", "").replace(",", "."); else entries[i][c] = '0.0'
});
entriesString += '&entry'+i+'=' + entries[i];
});
Now I'm new to JS and therefore do not know what the first $$('select[id=shopId]') part means.
It must be some sort of array or collection, due to the .each part it is followed by.
In that loop is again a nested loop that uses the loop variable i in its head.
But again, I don't know what exactly does %%('input[...]') mean. What kind of syntax is this?
Also, where does the data.
This is what entryString looks like for example:
&entry0=65.8,75.5,72.9,67.9,51.1,8.2,47.9&entry1=55.9,33.5,33.8,35.2,26.8,7.0,25.8
Thanks a lot or your help!
That looks like the $$ method of the Prototype library. The documentation is here:
http://www.prototypejs.org/api/utility#method-$$
It selects DOM elements given a CSS-style selector.
$$() is not something of javascript. It seems to be likely that you're using the Prototype Javascript Framework. Here you find the documentation of $$: http://api.prototypejs.org/language/dollardollar/
You are using the Prototype library.
See http://www.prototypejs.org/api/utility/dollar-dollar
your code uses the prototype JS framework. $$('ELEMENTNAME') instanciates all DOM element with ELEMENTNAME (so i.e. all input fields) and returns them as array of objects.
with id==xy it returns that one with id xy
<input type="blah" id="xy" value="123" />
will be found
It use a great function to get elements with css selectors.
I would like to get the currentStyle/computedStyle object and I dont want to manually check for the type of browser. (I wanted to get rid of cross-browser handling that is why I came to Jquery).
Actually I want the style object returning all the style-property: value map.
Please help.
Well, there is a soultion for a similiar problem offered by Keith Bentrup: jQuery CSS plugin that returns computed style of element to pseudo clone that element?
He used a list of attributes from Firebug and created a computed style object with jQuery to be able to clone styles from one object to another:
jQuery.fn.css2 = jQuery.fn.css;
jQuery.fn.css = function() {
if (arguments.length) return jQuery.fn.css2.apply(this, arguments);
var attr = ['font-family','font-size','font-weight','font-style','color',
'text-transform','text-decoration','letter-spacing','word-spacing',
'line-height','text-align','vertical-align','direction','background-color',
'background-image','background-repeat','background-position',
'background-attachment','opacity','width','height','top','right','bottom',
'left','margin-top','margin-right','margin-bottom','margin-left',
'padding-top','padding-right','padding-bottom','padding-left',
'border-top-width','border-right-width','border-bottom-width',
'border-left-width','border-top-color','border-right-color',
'border-bottom-color','border-left-color','border-top-style',
'border-right-style','border-bottom-style','border-left-style','position',
'display','visibility','z-index','overflow-x','overflow-y','white-space',
'clip','float','clear','cursor','list-style-image','list-style-position',
'list-style-type','marker-offset'];
var len = attr.length, obj = {};
for (var i = 0; i < len; i++)
obj[attr[i]] = jQuery.fn.css2.call(this, attr[i]);
return obj;
}
This seems to do exactly what you are looking for.
There are also a couple of plugins for that:
http://github.com/peol/jquery-computed-style
http://www.jupiterit.com/news/get-multiple-computed-styles-fast-with-the-curstyles-jquery-plugin
I'm writing a jquery-plugin, that changes a css-value of certain elements on certain user-actions.
On other actions the css-value should be reseted to their initial value.
As I found no way to get the initial css-values back, I just created an array that stores all initial values in the beginning.
I did this with:
var initialCSSValue = new Array()
quite in the beginning of my plugin and later, in some kind of setup-loop where all my elements get accessed I used
initialCSSValue[$(this)] = parseInt($(this).css('<CSS-attribute>'));
This works very fine in Firefox.
However, I just found out, that IE (even v8) has problems with accessing the certain value again using
initialCSSValue[$(this)]
somewhere else in the code. I think this is due to the fact, that I use an object ($(this)) as a variable-name.
Is there a way arround this problem?
Thank you
Use $(this).data()
At first I was going to suggest using a combination of the ID and the attribute name, but every object might not have an ID. Instead, use the jQuery Data functions to attach the information directly to the element for easy, unique, access.
Do something like this (Where <CSS-attribute> is replaced with the css attribute name):
$(this).data('initial-<CSS-attribute>', parseInt( $(this).css('<CSS-attribute>') ) );
Then you can access it again like this:
$(this).data('initial-<CSS-attribute>');
Alternate way using data:
In your plugin, you could make a little helper function like this, if you wanted to avoid too much data usage:
var saveCSS = function (el, css_attribute ) {
var data = $(el).data('initial-css');
if(!data) data = {};
data[css_attribute] = $(el).css(css_attribute);
$(el).data('initial-css', data);
}
var readCSS = function (el, css_attribute) {
var data = $(el).data('initial-css');
if(data && data[css_attribute])
return data[css_attribute];
else
return "";
}
Indexing an array with a jQuery object seems fishy. I'd use the ID of the object to key the array.
initialCSSValue[$(this).attr("id")] = parseInt...
Oh please, don't do that... :)
Write some CSS and use the addClass and removeClass - it leaves the styles untouched afterwards.
if anybody wants to see the plugin in action, see it here:
http://www.sj-wien.at/leopoldstadt/zeug/marcel/slidlabel/jsproblem.html
I have a bunch of input elements that have a particular substring in their IDs. Using javascript, is there a way to get these elements as an array? I wouldn't know the full ID - only the substring.
Is this any simpler if I use JQuery?
How about a non-jQuery answer...hmmm!?
function getAndFilter(elems, filter) {
var length = elems.length,
ret = [];
while (length--) {
if(filter(elems[length])) {
ret[ret.length] = elems[length];
}
}
return ret;
}
getAndFilter(document.getElementsByTagName('input'), function(input) {
// Your custom logic/rule goes here:
return input.id.substr(0,5) === 'HELLO';
});
Quite easy with jQuery. Example:
$("li[id^='comment']")
Select all "li" where id starts with "comment".
EDIT
To get those into an array:
var myArray = new Array;
$("li[id^='comment']").each(function() {
var thisId = $(this).attr("id");
myArray.push(thisId);
});
its simpler if you use jquery, otherwise you will have to start from document body, get its children, parse their ids, select matching elements, and continue down the tree.
jquery is definitely a good way to go.
Check out the attribute filters at jquery.com
Selectors API runs.
document.querySelectorAll("input[id*='yoursubstring']")
Works in IE8+, WebKit (Google Chrome, Safari), seems will work in next Opera and FF.