jQuery hasClass for any other attribute name - javascript

hasClass is useful when I want to check if the element has some class. I want to do the same check for some other attribute. For example, I use
<div id="nav" data-available-for="users administrators guests"></div>
and want to check if this div is available for users. So, I would do it like
$('#nav').hasAttributeValue('data-available-for', 'users')
Are there any existing beautiful tiny solutions for this?

There is no need to explode strings or use indexOf. jQuery has a complete set of css-selectors build in and so you can use attribute-selectors.
you can combine .is() and attribute-selectors:
if( $('#nav').is('[data-available-for~="users"]') ) { ..
http://api.jquery.com/category/selectors/
http://api.jquery.com/attribute-contains-word-selector/

It's pretty straightforward:
$('#nav').attr('data-available-for').indexOf('users') != -1
You can make a jquery helper out of it.

I think you're looking for attr:
if ($('#nav').attr('data-available-for').split(' ').indexOf('users') != -1) {
// do stuff
}
Similarly, you can set attributes by passing a new value for the attribute as the second argument:
$('#nav').attr('data-available-for', 'users'); // data-available-for="users"

You can take advantage of CSS Selector:
if ($("#nav[data-available-for~=user]").length) {
// is available for 'user'
}
Or if you prefer have the element not mixed with the condition:
if ($("#nav").filter("[data-available-for~=user]").length) {
// is available for 'user'
}
Of course you can build a function on top of it that makes it more readable for you.

I would try to use some native javascript before falling back on a library.
<div id='strawberry-plant' data-fruit='12'></div>
<script>
var plant = document.getElementById('strawberry-plant');
//'Getting' data-attributes using getAttribute
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Where it's implemented you can use the dataset attribute on the serialized DOM object
<div id='sunflower' data-leaves='47' data-plant-height='2.4m'></div>
<script>
// 'Getting' data-attributes using dataset
var plant = document.getElementById('sunflower');
var leaves = plant.dataset.leaves; // leaves = 47;
// 'Setting' data-attributes using dataset
var tallness = plant.dataset.plantHeight; // 'plant-height' -> 'plantHeight'
plant.dataset.plantHeight = '3.6m'; // Cracking fertiliser
</script>
additionally you can use some really powerful selecting with querySelectorAll like this
<script>
// Select all elements with a 'data-flowering' attribute
document.querySelectorAll('[data-flowering]');
// Select all elements with red leaves
document.querySelectorAll('[data-foliage-colour="red"]');
</script>
querySelectorAll() is supported by almost 90% of people online according to caniuse.com
http://caniuse.com/queryselector
and that is just the start. check out the full power of css3 query selectors here:
http://www.w3.org/TR/selectors/#selectors

Related

How do I extract part of a class starting with "xxx-" using jQuery

<body class="some-class xxx-term-i-want-to-extract some-other-class">
How do I extract "term-i-want-to-extract" from the body class, knowing that this always starts with "xxx-"?
Edit: The question is about getting "term-i-want-to-extract" and storing it inside a variable, for instance. Not about removing it from the body classes or returning the body classes without it. Thanks for your answers!
You can use the classList to get a list of all the classes the body tag has, and then use the $.map function to go over them and return only the relevant ones (after removed the xxx- string).
var classes = $.map($('body')[0].classList, function(cls, i) {
if (cls.indexOf('xxx-') === 0) {
return cls.replace('xxx-', '');
}
})
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="some-class xxx-term-i-want-to-extract some-other-class">
Here's a JSfiddle
// get the jQuery element
var $body = $('body');
// get the contents of the `class` attribute
// and use String#split to divide it into an
// array of individual class strings
var classes = $body.attr('class').split(' ');
// Array#find is used to find the first class
// that starts with the selected pattern
// and then the pattern is sliced off of the
// full class string
var xxx = classes.find(function (className) {
return className.startsWith('xxx-');
}).slice(4);
xxx === 'term-i-want-to-extract'; // true
Array#find and String#startsWith are part of the ES2015 specification and therefore may not be available on all platforms. You may then need to use polyfills in older browsers like IE:
startsWith polyfill
find polyfill

html "data-" attribute as javascript parameter

Lets say I have this:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this.data.uid, this.data-name, this.data-value)">
And this:
function fun(one, two, three) {
//some code
}
Well this is not working but I have absolutely no idea why. could someone post a working example please?
The easiest way to get data-* attributes is with element.getAttribute():
onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"
DEMO: http://jsfiddle.net/pm6cH/
Although I would suggest just passing this to fun(), and getting the 3 attributes inside the fun function:
onclick="fun(this);"
And then:
function fun(obj) {
var one = obj.getAttribute('data-uid'),
two = obj.getAttribute('data-name'),
three = obj.getAttribute('data-value');
}
DEMO: http://jsfiddle.net/pm6cH/1/
The new way to access them by property is with dataset, but that isn't supported by all browsers. You'd get them like the following:
this.dataset.uid
// and
this.dataset.name
// and
this.dataset.value
DEMO: http://jsfiddle.net/pm6cH/2/
Also note that in your HTML, there shouldn't be a comma here:
data-name="bbb",
References:
element.getAttribute(): https://developer.mozilla.org/en-US/docs/DOM/element.getAttribute
.dataset: https://developer.mozilla.org/en-US/docs/DOM/element.dataset
.dataset browser compatibility: http://caniuse.com/dataset
If you are using jQuery you can easily fetch the data attributes by
$(this).data("id") or $(event.target).data("id")
The short answer is that the syntax is this.dataset.whatever.
Your code should look like this:
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset.uid, this.dataset.name, this.dataset.value)">
Another important note: Javascript will always strip out hyphens and make the data attributes camelCase, regardless of whatever capitalization you use. data-camelCase will become this.dataset.camelcase and data-Camel-case will become this.dataset.camelCase.
jQuery (after v1.5 and later) always uses lowercase, regardless of your capitalization.
So when referencing your data attributes using this method, remember the camelCase:
<div data-this-is-wild="yes, it's true"
onclick="fun(this.dataset.thisIsWild)">
Also, you don't need to use commas to separate attributes.
HTML:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this)">
JavaScript:
function fun(obj) {
var uid= $(obj).attr('data-uid');
var name= $(obj).attr('data-name');
var value= $(obj).attr('data-value');
}
but I'm using jQuery.
JS:
function fun(obj) {
var uid= $(obj).data('uid');
var name= $(obj).data('name');
var value= $(obj).data('value');
}
you might use default parameters in your function
and then just pass the entire dataset itself, since the
dataset is already a DOMStringMap Object
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">
<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) {
//
}
</script>
that way, you can deal with any data-values that got set in the html tag,
or use defaults if they weren't set - that kind of thing
maybe not in this situation, but in others, it might be advantageous to put all
your preferences in a single data-attribute
<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">
there are probably more terse ways of doing that, if you already know
certain things about the order of the data
<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">

Select all elements with a "data-xxx" attribute without using jQuery

Using only pure JavaScript, what is the most efficient way to select all DOM elements that have a certain data- attribute (let's say data-foo).
The elements may be different, for example:
<p data-foo="0"></p><br/><h6 data-foo="1"></h6>
You can use querySelectorAll:
document.querySelectorAll('[data-foo]');
document.querySelectorAll("[data-foo]")
will get you all elements with that attribute.
document.querySelectorAll("[data-foo='1']")
will only get you ones with a value of 1.
document.querySelectorAll('[data-foo]')
to get list of all elements having attribute data-foo
If you want to get element with data attribute which is having some specific value e.g
<div data-foo="1"></div>
<div data-foo="2"></div>
and I want to get div with data-foo set to "2"
document.querySelector('[data-foo="2"]')
But here comes the twist ... what if I want to match the data attirubte value with some variable's value? For example, if I want to get the elements where data-foo attribute is set to i
var i=2;
so you can dynamically select the element having specific data element using template literals
document.querySelector(`[data-foo="${i}"]`)
Note even if you don't write value in string it gets converted to string like if I write
<div data-foo=1></div>
and then inspect the element in Chrome developer tool the element will be shown as below
<div data-foo="1"></div>
You can also cross verify by writing below code in console
console.log(typeof document.querySelector(`[data-foo="${i}"]`).dataset('dataFoo'))
why I have written 'dataFoo' though the attribute is data-foo reason dataset properties are converted to camelCase properties
I have referred below links:
MDN: data-*
MDN: Using data attributes
Try it → here
<!DOCTYPE html>
<html>
<head></head>
<body>
<p data-foo="0"></p>
<h6 data-foo="1"></h6>
<script>
var a = document.querySelectorAll('[data-foo]');
for (var i in a) if (a.hasOwnProperty(i)) {
alert(a[i].getAttribute('data-foo'));
}
</script>
</body>
</html>
Here is an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:
It does dynamically create a style rule [...] It then scans the whole document (using the
much decried and IE-specific but very fast document.all) and gets the
computed style for each of the elements. We then look for the foo
property on the resulting object and check whether it evaluates as
“bar”. For each element that matches, we add to an array.
Native JavaScript's querySelector and querySelectorAll methods can be used to target the element(s). Use a template string if your dataset value is a variable.
var str = "term";
var term = document.querySelectorAll(`[data-type=${str}]`);
console.log(term[0].textContent);
var details = document.querySelector('[data-type="details"]');
console.log(details.textContent);
<dl>
<dt data-type="term">Thing</dt>
<dd data-type="details">The most generic type.</dd>
</dl>
var matches = new Array();
var allDom = document.getElementsByTagName("*");
for(var i =0; i < allDom.length; i++){
var d = allDom[i];
if(d["data-foo"] !== undefined) {
matches.push(d);
}
}
Not sure who dinged me with a -1, but here's the proof.
http://jsfiddle.net/D798K/2/
While not as pretty as querySelectorAll (which has a litany of issues), here's a very flexible function that recurses the DOM and should work in most browsers (old and new). As long as the browser supports your condition (ie: data attributes), you should be able to retrieve the element.
To the curious: Don't bother testing this vs. QSA on jsPerf. Browsers like Opera 11 will cache the query and skew the results.
Code:
function recurseDOM(start, whitelist)
{
/*
* #start: Node - Specifies point of entry for recursion
* #whitelist: Object - Specifies permitted nodeTypes to collect
*/
var i = 0,
startIsNode = !!start && !!start.nodeType,
startHasChildNodes = !!start.childNodes && !!start.childNodes.length,
nodes, node, nodeHasChildNodes;
if(startIsNode && startHasChildNodes)
{
nodes = start.childNodes;
for(i;i<nodes.length;i++)
{
node = nodes[i];
nodeHasChildNodes = !!node.childNodes && !!node.childNodes.length;
if(!whitelist || whitelist[node.nodeType])
{
//condition here
if(!!node.dataset && !!node.dataset.foo)
{
//handle results here
}
if(nodeHasChildNodes)
{
recurseDOM(node, whitelist);
}
}
node = null;
nodeHasChildNodes = null;
}
}
}
You can then initiate it with the following:
recurseDOM(document.body, {"1": 1}); for speed, or just recurseDOM(document.body);
Example with your specification: http://jsbin.com/unajot/1/edit
Example with differing specification: http://jsbin.com/unajot/2/edit

jquery selector for multiple classes

I have elements in my DOM with class="LiveVal:variablepart" and i would like to write a JQuery selector that works even if the elements have other classes on tom of the above. Eg. class="header LiveVal:varablepart" or class="LiveVal:varablepart header".
It works fro me if LiveVal is the first class with:
$('[class^=LiveVal:]').each(function ( intIndex ) { somefunction });
but obviously not if another class is before LiveVal.
In the function I need to extract the variable part. I planned to do like this:
theclass = $( this ).attr('class');
varpart = theclass.replace('\bLiveVal:(.+?)[\s]', '$1');
..but alas, it doesn't match. I've tested the regex on http://gskinner.com/RegExr/ where it seems to work, but it doesn't in javascript !?
Any help would be greatly appreciated.
This will check if a class name contains 'LiveVal:'
$('[class*=LiveVal:]').each(function ( intIndex ) { somefunction });
EDIT
did not realise you had that requirement (although a good one). You can do this instead: $('[class^="LiveVal:"], [class*=" LiveVal:"]')
Here is a fiddle: http://jsfiddle.net/wY8Mh/
It might be somewhat faster to do this with an explicit filter:
$("*").filter(function() { return /\bLiveVal:/.test(this.className); }).something();
It depends on whether the native "querySelectorAll" does the work, and does it quickly. This also would avoid the "FooLiveVal" problem.
It's worth noting that in an HTML5 world, it might be better to use a "data-LiveVal" attribute to store that "variable part" information on your elements. Then you could just say:
$('[data-LiveVal]').something();
In the HTML, it'd look like this:
<div class='whatever' data-LiveVal='variable part'>
Since version 1.5, jQuery will fetch stuff in a "data-foo" attribute when you pass the tail of the attribute (the part after "data-") to the ".data()" method:
var variablePart = $(this).data('LiveVal');
The ".data()" method will not, however, update the "data-foo" property when you store a new "variable part".
edit — if you want the value that's stuffed into the class after your property name prefix ("LivaVal:"), you can extract it like this:
var rLiveVal = /\bLiveVal:(\S*)\b/;
$('*').filter(function() { return rLiveVal.test(this.className); }).each(function() {
var variablePart = rLiveVal.exec(this.className)[1];
//
// ... do something ...
//
});
(or some variation on that theme).

Setting properties on anonymous DOM elements through JavaScript?

Let's say I'm generating markup through server-side code. I'm generating a bunch of HTML tags but I want to add custom client-side behavior.
With JavaScript (if I had a reference to the DOM node) I could have written:
var myDOMNode = ...
myDOMNode.myCustomAttribute = "Hi!";
Now the issue here is that I don't want to qualify every element with an unique id just to initialize data. And it's really strange to me, that there's not an easier and unobtrusive way to attach client-side behavior.
If I'm remembing this correctly, this is valid IE stuff.
<div onload="this.myCustomAttribute='Hi!'"></div>
If I was able to do this, I should be able to access it's "data context" though the identifier 'myCustomAttribute', which is really what I want.
The following will work but not validate:
<div myattribute="myvalue"></div>
But if you are injecting it into the HTML with Javascript, then perhaps that's not concern for you. Otherwise, you can use something like jQuery to process the elements before adding them to the DOM:
$(elements).each(function(){
$(this).attr('myattribute','myvalue');
});
First off you should access custom attributes using the getAttribute and setAttribute methods if you want your code to work on other browsers than IE.
As to your event handler question that really depends on how you add the event handler.
Assigning a function directly to the elements onXXXX property would allow you access the the element via this.
If you use IE's attachEvent you can't use this, you can access the element that generated the event using event.srcElementbut that may be child element of the div. Hence you will need to test for the existance of myCustomAttribute and search up the ancestors until you find it.
I do appricate the input but I've finally figured this out and it's the way I go about initialization that has been the thorn in my side.
What you never wan't do is to pollute your global namespace with a bunch of short lived identifiers. Any time you put id="" on an element you're doing exactly that (same thing for any top level function). By relying on jQuery, HTML5 data and CSS there's a solution to my problem which I think is quite elegant.
What I do is that I reserve a CSS class for a specific behavior and then use HTML5 data to parameterize the behavior. When the document is ready, I query the document (using Query) for the CSS class that represents the behavior and initialize the client-side behavior.
I've been doing a lot of ASP.NET and within this context both the id="" and name="" belongs to ASP.NET and is pretty useless for anything else than internal ASP.NET stuff. What you typically find yourself doing is to get at a server-side property called ClientID you can refer to this from client-side JavaScript, it's a lot of hassle. They made it easier in 4.0 but fundamentally I think it's pretty much broken.
Using this hybrid of CSS, HTML5 data and jQuery solves this problem altogether. Here's an example of an attached behavior that uses regular expressions to validate the input of a textbox.
<input type="text" class="-input-regex" data-regex="^[a-z]+$" />
And here's the script:
$(function () {
function checkRegex(inp) {
if (inp.data("regex").test(inp.val()))
inp.data("good-value", inp.val());
else
inp.val(inp.data("good-value"));
}
$(".-input-regex")
.each(function () {
// starting with jQuery 1.5
// you can get at HTML5 data like this
var inp = $(this);
var pattern = inp.data("regex");
inp.data("regex", new RegExp(pattern));
checkRegex(inp);
})
.keyup(function (e) {
checkRegex($(this));
})
.change(function (e) {
checkRegex($(this));
})
.bind("paste", undefined, function (e) {
checkRegex($(this));
})
;
});
Totally clean, no funky id="" or obtrusive dependency.
In HTML5 there are HTML5 data attributes introduced exactly for the case.
<!DOCTYPE html>
<div data-my-custom-attribute='Hi!'></div>
is now corect, validating html. You can use any name starting with data- in any quantity.
There is jQuery .data method for interaction with them. Use .data( key ) to get, .data(key, value) to set data-key attribute. For example,
$('div').each(function () {
$(this).html($(this).data('myCustomAttribute')).data('processed', 'OK');
});
How about this?
<script>
function LoadElement(myDiv)
{
alert(this.myCustomAttribute);
}
</script>
<div onload="LoadElement(this)"></div>
not tested btw
Since you're trying to do this for multiple elements, you may try name attributes and getElementsByName.
<div name="handleonload">...</div>
window.onload = function () {
var divs = document.getElementsByName('handleonload');
for (var i = 0; i < divs.length; i += 1) {
divs[i].foo = 'bar';
}
};
Alternatively, you can use selectors, using libraries (such as jQuery and Prototype) and their respective iterators. This will also allow for you to search by other attributes (such as class).
Though, be cautious with your terminology:
obj.property = value;
<tag attribute="value">
<div style="width:100px;height:100px;border:solid black 1px" myCustomAttribute='Hi!' onclick="alert(myCustomAttribute);"></div>
The onload event is used for server side events. Its not part of the standard html element events.
Take a look at the following functions (especially the walk_the_dom one):
// walk_the_DOM visits every node of the tree in HTML source order, starting
// from some given node. It invokes a function,
// passing it each node in turn. walk_the_DOM calls
// itself to process each of the child nodes.
var walk_the_DOM = function walk(node, func) {
func(node);
node = node.firstChild;
while (node) {
walk(node, func);
node = node.nextSibling;
}
};
// getElementsByAttribute takes an attribute name string and an optional
// matching value. It calls walk_the_DOM, passing it a
// function that looks for an attribute name in the
// node. The matching nodes are accumulated in a
// results array.
var getElementsByAttribute = function (att, value) {
var results = [];
walk_the_DOM(document.body, function (node) {
var actual = node.nodeType === 1 && node.getAttribute(att);
if (typeof actual === 'string' &&
(actual === value || typeof value !== 'string')) {
results.push(node);
}
});
return results;
};
With the above two functions at hand, now we can do something like this:
some link
<script>
var els = getElementsByAttribute('dreas');
if (els.length > 0) {
els[0].innerHTML = 'changed text';
}
</script>
Notice how now I am making finding that particular element (which has an attribute called dreas) without using an id or a class name...or even a tag name
Looks like jQuery is the best bet for this one based on my searching. You can bind an object to a DOM node by:
var domNode = ...
var myObject = { ... }
$(domNode).data('mydata', mymyObj);
then you can call the data back up the same way, using your key.
var myObect = $(domNode).data('mydata');
I assume you could also store a reference to this within this object, but that may be more info then you really want. Hope I could help.

Categories

Resources