jQuery select elements which contain specified item in an array data attribute - javascript

I have an element which I'd like to give a data attribute which contains a series of values, i.e., an Array. Then I'd like to be able to select it based on any of the values in that series. Something like this:
<div id="example" data-my-series='["foo", "bar"]'></div>
Then I was hoping to select it based on the fact that it has "foo" in it. I'm not really sure how I'd go about it, though. I know I'd do $('div[data-my-series="foo"]') if I wasn't taking this approach, but, obviously that's not the case. Any suggestions?
Edit: Also, how can I achieve the inverse of this? i.e., select an element which does not have "foo" in its data-my-series?

$( "[data-my-series*='foo']" )
Here ya go!

The simplest way is very similar to what you are doing, just use the Attribute Contains Selector instead of the equals selector: $('div[data-my-series*="foo"]')
You can see more about it here:
http://api.jquery.com/attribute-contains-selector/
Edit:
To answer the comment below, you can layer selectors in jQuery so take a look at the ":not()" selector. The usage would be $('div:not([data-my-series*="foo"])').
Make sure you don't put the div inside the :not. Also you will probably want to add [data-my-series] outside the :not as well to make sure you only select divs that have that data attribute.
Final product:
$('div[data-my-series]:not([data-my-series*="foo"])')

Watch out. The accepted answer will do substring matching and probably result in matches you didn't intend.
$('[data-my-series*="foo"]') will not just find <div data-my-series="foo"> but will also include <div data-my-series="foobar"> in the results
You should use ~ instead of * to do whole-word matching $('[data-my-series~="foo"]'). This will result in matching foo but not foobar
If you want multiple words in the data string, use spaces to separate them:
http://api.jquery.com/attribute-contains-word-selector/

Related

Selecting element with specific class and value

How to select element with class MyClass and value MyValue, but without using each?
I tried something like:
$(".MyClass").find("[value='MyValue']")
$(".MyClass[value='MyValue']")
This is example: http://jsfiddle.net/HQaG5/
It works if i use hard coded value for select element.
You want :contains() :
$( ".MyClass:contains('MyValue')" )
Take a look here: jquery find element by text
You can use the :contains selector to find elements containing text.
But if you want to match an exact string then .filter is the better option
If the element is an input and you want to search after property value you can use .filter()
$('.MyClass').filter(function(){
return this.value=="MyValue";
});
DEMO
If you are looking to get the select box element that has the specified value selected (which seems to be the case based on your fiddle), then you can use this…
$(".MyClass option:selected[value='MyValue']").parent()
DEMO
However, I would question why you want to do this, as it seems kind of backwards.

Multiple not() DOM Selectors

I want to select a particular node with two not clauses, but I had no success so far. What I need to do is, select an element whose div contains the string 0008, but it's not 10008 and also it does not contain the tag "style", so, in theory it should work like that:
document.querySelectorAll(" div[id*='0008']:not([id='10008'][style])")
However, as you might suspect, it doesn't work that way.
document.querySelectorAll(" div[id*='0008']:not([id='10008'])")
document.querySelectorAll(" div[id*='0008']:not([style])")
Both of them work perfectly individually, of course.
not 10008 and also it does not …
That's not what your current selector checks, it test whether it has not ( the id and a style attribute ) . Use this instead:
div[id*='0008']:not([id='10008']):not([style])
Your original solution also was not a valid selector, since :not() may only contain one simple selector, while you had two of them. Yet, selector libraries like jQuery's sizzle engine might support them. So with jQuery, the following would work as well:
div[id*='0008']:not([id='10008'],[style])
jsFiddle Demo
Logically, you are trying to exclude elements that match either of the two undesired selectors, not elements that match them both. In jQuery, the multiple selector (which will then match all of the undesired elements, then be negated) is simply a comma-separated listing. Therefore you simply do this:
$("div[id*='0008']:not([id='10008'],[style])")
From the jQuery docs (since this question is tagged jQuery):
All selectors are accepted inside :not(), for example: :not(div a) and :not(div,a).
I'd just do:
var elems = $('div[id*="0008"]').filter(function() {
return !this.hasAttribute("style") && this.id == '10008';
});
I don't think I really get this, but this would filter out:
<div id="10008" style="color: black">10008</div>
but not:
<div id="10008">10008</div>
ID's are of course unique, and there could be a real world use case for this, but it still seems like an edge case that you'd normally handle some other way, as once you'd filtered out the ID, why exactly do you need to match a style tag as well ?

jquery slideToggle on all open div s

i have div s with id like that:
manufacturer_12,
manufacturer_37,
manufacturer_71,
etc...
is there a way to find all the div s which their visibility is visible, and to do to them something like:
$('[id^="manufacturer"]').slideToggle("slow");
the problem is that its imposibble to make a for loop because their id isn't consecutive.
maybe i should use http://api.jquery.com/jQuery.each/ ?
You could use .each, but this may work:
$("[id^='manufacturer']:visible").slideToggle("slow");
Indeed, you can use :visible.
$('[id^="manufacturer"]').filter(":visible").slideToggle("slow");
But be aware that .slideToggle() will apply to all matched elements as the documentation says. So, you actually don't need to use .each() here.
.slideToggle( [duration] [, callback] )
Returns: jQuery
Description: Display or hide the matched elements with a sliding motion.
In this case, all visible elements with id starting with manufacturer.
Believe me, that's not a good way of doing things.
You'd better assign a specific class to all items of interest and write a very simple selector basing on class name only. This will work much faster.

What is the jQuery equivalent to document.forms[0].elements[i].value;?

What is the jquery equivalent to: document.forms[0].elements[i].value;?
I don't know how to travel through a form and its elements in jQuery and would like to know how to do it.
The usual translation is the :input selector:
$("form:first :input").each(function() {
alert($(this).val()); //alerts the value
});
The :first is because your example pulls the first <form>, if there's only one or you want all input elements, just take the :first off. The :input selector works for <input>, <select>, <textarea>...all the elements you typically care about here.
However, if we knew exactly what your goal is, there's probably a very simple way to achieve it. If you can post more info, like the HTML and what values you want to extract (or do something else with).
Well, translated literally, it'd be:
$('form:first *:nth-child(i)').val()
But jQuery makes it easy to grab elements by other manners such as ID or CSS selector. It'd be easier to maintain if you did something like:
$('form#id input.name').val()
$("#formid input").each(function(){
alert($(this).attr("value"))
})
This will give you all elements under the form. Including non form elements:
$("#[form id]").find()
Then you can use an each function to traverse all the children. Or you can use the input selector to only return the form elements:
$("#[form id] :input")
I'm not exactly sure what you're trying to accomplish, but you should be able to do something like this:
$('form:first').children(':first').val();
This will get the value of the first child node within the first <form> tag in the DOM.

JQuery, how to find list of div's with similar ID

I have a structure of html like this:
<div id="triger1">some elements inside</div>
<div id="triger2">some elements inside</div>
<div id="triger3">some elements inside</div>
<div id="triger4">some elements inside</div>
How do I get array of all the div's in JQuery with the triger ID in them (as you can see, they all have triger but different numbering eg. triger1, triger2 etc...)
You can use the following:
$("div[id^='triger']")
This will return all <div> with id starting (^=) with triger.
You can get more information about the various jQuery selectors in the jQuery docs:
API/Selectors
you can actually use a regular expression in a selector to achieve exactly what you are looking for, as such:
$("div:regex(id, yourRegularExpression)");
(Note: this does require the regex-selector plugin)
Someone asked a similar question here.
You can read all about regular expressions here.
As others have pointed out, you can achieve the same result like this:
$("div[id^='partOfID']");
by using a simple jQuery selector. For more complex selections, though, you will need to use the regex plugin or do it manually, as noted in the linked question.
good luck!
Select all div elements whose id attribute contains the string triger:
$('div[id*="triger"]');
There's more about using *= in the jQuery documentation: Attribute Contains Selector [name*="value"]
var trigerList = $("div[id^='triger']");

Categories