I'm trying to check a set of divs with id='checkbox-selector-chosen' to see if a dynamic variable name exists in those divs. The code below works only if one 'checkbox-selector-chosen' div exists. What I'm trying to do is get the code below to check all of the 'checkbox-selector-chosen' divs for the existence of name.
if($(".checkbox-selector-chosen").text() == name) {
do something...
}
The structure of the divs I'm working with is as follows:
<div id="selected-results" class="group">
<div class="checkbox-selector-chosen">John</div>
<div class="checkbox-selector-chosen">Dave</div>
<div class="checkbox-selector-chosen">Jack</div>
</div>
I'm new to JS/JQuery and I'm sure this is a simple problem, but after 2 days of banging my head against my desk I've decided to ask on here.
Any help will be greatly appreciated!
You may want to use the :contains() selector to see if the item exists (JsFiddle Demo)
var name='Dave';
//Get all items that contain 'Dave'
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
if (items.length > 0) {
alert(items.length + ' items found');
}
UPDATE
If you're worried about having more than one matching item, you can use my example, AND the each() function. (JsFiddle Demo). The Beauty of this approach is that you do not have to loop through all of the child divs - you only need to loop through the divs that contain the desired matching text.
var name='Dave';
//Get all items that contain 'Dave'
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
if (items.length > 0) {
items.each(function(){
if ($(this).html()==name){
alert('item found!');
break;
}
});
}
UPDATE 2
Here is an example which demonstrates the full use of this technique. When you click on a name div, the name is parsed from the object that is clicked and the we use the above method to find the right div. This is, of course, not the best way to accomplish this specific task, but simple illustrates the concept. (JsFiddle Demo)
function findName(name){
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
$('.checkbox-selector-chosen').css({'background':'#fff'});
if (items.length > 0) {
items.each(function(){
if ($(this).text()==name){
$(this).css({'background':'#ff0'});
}
});
}
}
$('.checkbox-selector-chosen').click(function(){
findName($(this).text());
});
Your class selector returns a collection of matches. You could try each() to iterate over them:
$(".checkbox-selector-chosen").each( function() {
if ($(this).text() == name) {
/* ..do something... */
} } );
$('.checkbox-selector-chosen').each(function(){
if($(this).text() == name) {
do something...
}
});
Maybe this is what you're looking for?
ahh beaten to it!
You can user jquery 'each' syntax for this.
$(".checkbox-selector-chosen").each(function(index, value){
console.info("index = "+index +" = "+value);
if(value == name){
console.info("match");
}
});
You want to use jQuery :contains() selector.
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title></title>
</head>
<body>
<div id="selected-results" class="group">
<div class="checkbox-selector-chosen">John</div>
<div class="checkbox-selector-chosen">Dave</div>
<div class="checkbox-selector-chosen">Jack</div>
</div>
<script type="text/javascript">
jQuery(".checkbox-selector-chosen:contains(John)").css("background-color","red")
</script>
</body>
</html>
JSBIN
You could use the contains() selector to filter the results:
$('input[type="checkbox"]').change(function(){
var checked = this.checked;
$('.checkbox-selector-chosen')
.filter(":contains("+this.value+")")
.css('color',function(){
if (checked) return "red";
else return "black";
});
});
example: http://jsfiddle.net/niklasvh/mww3J/
Related
I'd like to select an element using javascript/jquery in Tampermonkey.
The class name and the tag of the elements are changing each time the page loads.
So I'd have to use some form of regex, but cant figure out how to do it.
This is how the html looks like:
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
The tag always is the same as the classname.
It's always a 4/5 letter random "code"
I'm guessing it would be something like this:
$('[/^[a-z]{4,5}/}')
Could anyone please help me to get the right regexp?
You can't use regexp in selectors. You can pick some container and select its all elements and then filter them based on their class names. This probably won't be super fast, though.
I made a demo for you:
https://codepen.io/anon/pen/RZXdrL?editors=1010
html:
<div class="container">
<abc class="abc">abc</abc>
<abdef class="abdef">abdef</abdef>
<hdusf class="hdusf">hdusf</hdusf>
<ueff class="ueff">ueff</ueff>
<asdas class="asdas">asdas</asdas>
<asfg class="asfg">asfg</asfg>
<aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>
js (with jQuery):
const $elements = $('.container *').filter((index, element) => {
return (element.className.length === 5);
});
$elements.css('color', 'red');
The simplest way to do this would be to select those dynamic elements based on a fixed parent, for example:
$('#parent > *').each(function() {
// your logic here...
})
If the rules by which these tags are constructed are reliably as you state in the question, then you could select all elements then filter out those which are not of interest, for example :
var $elements = $('*').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
DEMO
Of course, you may want initially to select only the elements in some container(s). If so then replace '*' with a more specific selector :
var $elements = $('someSelector *').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
You can do this in vanilla JS
DEMO
Check the demo dev tools console
<body>
<things class="things">things</things>
<div class="stuff">this is not the DOM element you're looking for</div>
</body>
JS
// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;
// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
var tagName = el.tagName.toLowerCase();
var classlistVal = el.classList.value.toLowerCase();
if (tagName === classlistVal) { return el; }
});
targets.forEach(function(el) {
// Do stuff
console.log(el)
})
I need to find the closest parent that contains the following css property:
background-image: url(*here goes a link to a valid image*);
Finding it could probably be done via selecting all elements, filtering them in an array, then using the first/last element of the array, but I'd like to know if there's a faster way to select the closest parent that fulfills the requirement I mentioned before, like this:
<parent1 style="background-image:url(http://google.com/images/photo.png);">
<parent2 style="background-image:url('http://google.com/images/photo.png');">
<mydiv></mydiv>
</parent2>
</parent1>
I want the parent2 selected;
Keep in mind that I do not know the background url.
You can extend the jQuery selector to allow for this. And with your specific rules.
Something like this:
$.extend($.expr[':'], {
backgroundValid: function(a) {
//change the url for what you want
return $(a).css('background-image') === "url(http://stacksnippets.net/validurl)";
}
});
var test = $('.foo').closest('div:backgroundValid');
console.log(test) //prints bar
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-image:url('validurl');">
<div class="bar" style="background-image:url('validurl');">
<div class="foo"></div>
</div>
</div>
There is no need to filter all parents, just make it recursive like this jsfiddle
html
<div id="parent1" style="background-image:url(validurl);">
<div id="parent2" style="background-image:url(validurl);">
<div id="start"></div>
</div>
</div>
javascript
$(function() {
var cssKey = "background-image";
var element = $('#start');
var found = false;
while (!found) {
element = element.parent();
found = element.css(cssKey) == 'none' ? false : true;
if (element.is($('html'))) break;
}
if (found) {
console.log(element.attr('id'));
} else {
console.log('Not found');
}
});
Probably this can help you,
select the element
pick up all its parent
filter its parent by what you want!
var firstParent, URL_TO_MATCH = "url(HELLO WORLD)";
$('#foo').parents().filter(function() {
var isValid = $(this).css('background-image') == URL_TO_MATCH;
if(!firstParent && isValid) {
firstParent = $(this);
}
return isValid;
});
I'm trying to assign these css values (below) for the javascript line in the example below, but don't know a way to target valueB with the .valueB-class.
$(".valueA").html(valueA + " valueB" + ((valueA > 1) ? 's': ''));
.valueA-class { font-size:X }
.valueB-class { font-size:XX }
Here is an example of what I need help with (you may have to click on the input boxes in the results panel to get the calculations to show up - that's what I had to do): http://jsfiddle.net/hughett/g21g8t85/
Welcome to stackoverflow!
Your question seems a bit vague. I assume that this is you want to achieve. In the specific example the value of the class is changed through the use of the jquery attr function. Firstly, the specific div in which our text is placed is retrieved and then the value gets specified. I am attaching a code snippet below.
A general note, using a . in css indicates that you are referring to a class so there is no need to attach a -class in the name.
$( "#myButton" ).on( "click", function() {
var attr = $("#myText").attr('class');
console.log(attr);
if (attr == "valueA") {
$("#myText").attr("class","valueB");
} else {
$("#myText").attr("class","valueA");
}
});
.valueA { font-size:11pt }
.valueB { font-size:25pt }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Change Text size</button>
<div id="myText" class="valueA">sdsa asd aasdaas asdjlasj dasdkas asldjsalj slad TEST</div>
EDIT to include another answer
In order for the text included in a single span to have different font-size you need to separate it somehow. In the specific example, I have added a second span in the respective div and adjusted the cacl_summary method to get the expected result.
The code is available below; I have also updated the jsfiddle here
<div style="background:yellow;"><span class="label">Simple payback</span>
<span class="figure sp"></span> <span class="figure year"></span></div>
function calc_summary(){
if (cspy) {
sp = parseFloat($("input[name=upgrade]").val()) / cspy;
if (sp) {
sp = (sp < 100) ? sp.toString().substring(0, 4) : sp;
$(".sp").html(sp);
$(".year").html(" years" + ((sp > 1) ? 's': ''));
$(".ror").html(parseInt((1/sp) * 100) + '%');
}
}
}
I need to read elements class name. I have elements like this:
<article class="active clrone moreclass">Article x</article>
<article class="active clrtwo moreclass">Article y</article>
<article class="active clrthree moreclass moreclass">Article z</article>
<article class="active clrone moreclass">Article xyza</article>
I need to parse out class name that starts with clr. So if second element was clicked then I would need to get clrtwo className.
You can use a regular expression match on the class name of the clicked item to find the class that begins with "clr" like this:
$("article").click(function() {
var matches = this.className.match(/\bclr[^\s]+\b/);
if (matches) {
// matches[0] is clrone or clrtwo, etc...
}
});
Here is solution for you:
$('article').click(function () {
var className = this.className.split(' ');
for (var i = 0; i < className.length; i+=1) {
if (className[i].indexOf('clr') >= 0) {
alert(className[i]);
}
}
});
http://jsfiddle.net/vJfT7/
There's no matter how you're going to order the different classes. The code will alert you a class name only of there's 'clr' as a substring in it.
Best regards.
If you don't need to find elements based on these classes (e.g. doing $('.clrtwo')) it would be nicer to store the data as a data-clr attribute. This is standards-compliant from HTML5, and is supported by jQuery using the .data() function.
In this instance, I would modify your HTML in this way:
<article class="active moreclass" data-clr="one">Article x</article>
<article class="active moreclass" data-clr="two">Article y</article>
<article class="active moreclass moreclass" data-clr="three">Article z</article>
<article class="active moreclass" data-clr="one">Article xyza</article>
I would then use Javascript like this:
$('article.active').click(function() {
console.log($(this).data('clr'));
});
jsFiddle example
If it is always the second class name which is of interest you can do this:
$("article").click(function () {
// split on the space and output the second element
// in the resulting array
console.log($(this)[0].className.split(" ")[1]);
});
http://jsfiddle.net/karim79/Z3qhW/
<script type="text/javascript">
jQuery(document).ready(function(){
$("article").click(function(){
alert($(this).attr('class').match(/\bclr[^\s]+\b/)[0]);
});
});
</script>
This should jquery script should do what you asked (tested on jsfiddle):
$(document).ready(function () {
function getClrClass(elem) {
var classes = elem.getAttribute('class').split(' ');
var i = 0;
var cssClass = '';
for (i = 0; i < classes.length; i += 1) {
if (classes[i].indexOf('clr') === 0) {
cssClass = classes[i];
i = classes.length; //exit for loop
}
}
return cssClass;
};
$('article').click(function (e) {
var cssClass = getClrClass($(this)[0]);
alert(cssClass);
e.preventDefault();
return false;
});
});
Hope this helps.
Pete
Use an attribute selector to get those that have class names that contain clr.
From there:
extract the class name (string functions)
analyze the position
determine the next element
The latter two might be best served by a translation array if you only had a few classes.
UPDATE
I agree with lonesomeday, you'd be far better off using data-* attribute to handle such logic. Using CSS as JavaScript hooks is a thing of the past.
http://jsfiddle.net/4KwWn/
$('article[class*=clr]').click(function() {
var token = $(this).attr('class'),
position = token.indexOf('clr');
token = token.substring(position, token.indexOf(' ', position));
alert(token);
});
I have a div that contains many spans and each of those spans contains a single href.
Basically it's a tag cloud. What I'd like to do is have a textbox that filters the tag cloud on KeyUp event.
Any ideas or is this possible?
Updated question: What would be the best way to reset the list to start the search over again?
Basically, what you want to do is something like this
$('#myTextbox').keyup(function() {
$('#divCloud > span').not('span:contains(' + $(this).val() + ')').hide();
});
This can probably be improved upon and made lighter but this at least gives the functionality of being able to hide multiple tags by seperating your input by commas. For example: entering this, that, something into the input will hide each of those spans.
Demo HTML:
<div id="tag_cloud">
<span>this</span>
<span>that</span>
<span>another</span>
<span>something</span>
<span>random</span>
</div>
<input type="text" id="filter" />
Demo jQuery:
function oc(a){
var o = {};
for(var i=0;i<a.length;i++){
o[a[i]]='';
}
return o;
}
$(function(){
$('#filter').keyup(function(){
var a = this.value.replace(/ /g,'').split(',');
$('#tag_cloud span').each(function(){
if($(this).text() in oc(a)){
$(this).hide();
}
else {
$(this).show();
}
})
})
})