I have a div structure like
<div>
<div class='class1'>contens</div>
<div class='class2'>contens</div>
<div class='class2'>contens</div>
<div class='class2'>contens</div>
<div class='class3'>contens</div>
<div class='class2'>contens</div>
<div class='class1'>contens</div>
</div>
Here I want to write a selector which will select all the div elements with class='class2', they should be adjacent to each other. i.e I should select only index 1,2,3 but not div index 5 since its not adjacent to group.
Please Help here.
You can use the adjacent sibling selector
var elems = $('.class2 + .class2').add( $('.class2 + .class2').prev() )
FIDDLE
or caching the selector (with an argument to a IIFE)
var elems = (function(x) {return x.add( x.prev() )})($('.class2 + .class2'));
FIDDLE
Here is an alternative solution with .filter:
For example:
$('.class2').filter(function() {
return $(this).prev('.class2').add($(this).next('.class2')).length > 0;
});
It filters out the elements that don't have a sibling with class .class2.
Related
I'm trying to only show certain divs. The way I have decided to do this is to first hide all elements that start with "page" and then only show the correct divs. Here's my (simplified) code:
<form>
<input type="text" onfocus="showfields(1);">
<input type="text" onfocus="showfields(2);">
</form>
<div class="page1 row">Some content</div>
<div class="page1 row">Some content</div>
<div class="page2 row">Some content</div>
<div class="page2 row">Some content</div>
<script>
function showfields(page){
//hide all items that have a class starting with page*
var patt1 = /^page/;
var items = document.getElementsByClassName(patt1);
console.log(items);
for(var i = 0; i < items.length; i++){
items[i].style.display = "none";
}
//now show all items that have class 'page'+page
var item = document.getElementsByClassName('page' + page);
item.style.display = '';
}
</script>
When I console.log(items); I get a blank array. I'm pretty sure the regexp is right (get all items starting with 'page').
The code I'm using is old school JS, but I'm not adverse to using jQuery. Also if there is a solution that doesn't use regexp, that's fine too as I'm new to using regexp's.
getElementsByClassName only matches on classes, not bits of classes. You can't pass a regular expression to it (well, you can, but it will be type converted to a string, which is unhelpful).
The best approach is to use multiple classes…
<div class="page page1">
i.e. This div is a page, it is also a page1.
Then you can simply document.getElementsByClassName('page').
Failing that, you can look to querySelector and a substring matching attribute selector:
document.querySelectorAll("[class^=page]")
… but that will only work if pageSomething is the first listed class name in the class attribute.
document.querySelectorAll("[class*=page]")
… but that will match class attributes which mention "page" and not just those with classes which start with "page" (i.e. it will match class="not-page".
That said, you could use the last approach and then loop over .classList to confirm if the element should match.
var potentials = document.querySelectorAll("[class*=page]");
console.log(potentials.length);
elementLoop:
for (var i = 0; i < potentials.length; i++) {
var potential = potentials[i];
console.log(potential);
classLoop:
for (var j = 0; j < potential.classList.length; j++) {
if (potential.classList[j].match(/^page/)) {
console.log("yes");
potential.style.background = "green";
continue elementLoop;
}
}
console.log("no");
potential.style.background = "red";
}
<div class="page">Yes</div>
<div class="notpage">No</div>
<div class="some page">Yes</div>
<div class="pageXXX">Yes</div>
<div class="page1">Yes</div>
<div class="some">Unmatched entirely</div>
Previous answers contain parts of the correct one, but none really gives it.
To do this, you need to combine two selectors in a single query, using the comma , separator.
The first part would be [class^="page"], which will find all the elements whose class attribute begins with page, this selector is thus not viable for elements with multiple classes, but this can be fixed by [class*=" page"] which will find all the elements whose class attribute have somewhere the string " page" (note the space at the beginning).
By combining both selectors, we have our classStartsWith selector:
document.querySelectorAll('[class^="page"],[class*=" page"]')
.forEach(el => el.style.backgroundColor = "green");
<div class="page">Yes</div>
<div class="notpage">No</div>
<div class="some page">Yes</div>
<div class="pageXXX">Yes</div>
<div class="page1">Yes</div>
<div class="some">Unmatched entirely</div>
You can use jQuery solution..
var $divs = $('div[class^="page"]');
This will get all the divs which start with classname page
$(document).ready(function () {
$("[class^=page]").show();
$("[class^=page]").hide();
});
Use this to show hide div's with specific css class it will show/hide all div's with css class mention.
I am trying to count the number of it's first layer of children not including it's child of child of child.. This is my codes
HTML
<div class="container">
<div class="row">
<div class="btn-container col-md-12">
Hello
</div>
</div>
</div>
JS
$('a').click(function(){
var c = $(this).closest('.row').clone();
$(this).after( c );
var count = $(this).closest('.row').find('.btn-container').length;
alert(count);
});
The alert should always return 1 since the cloned element is appended inside of it.
jsFiddle
I tried ..
.find() but also as I expected, it will count all inside of it.. Child of child of child and so on...
var parent = $(this).closest('.row');
var count = $('.btn-container', parent).length;
But still can not get what I want.
I already think of adding a name/class specifying to them. Like btn-container first-children ..
But I am wondering if there is a jQuery trick that will make it simplier.
find('.btn-container') will select all descendants .btn-container. You should use direct child selector > like following.
$('a').click(function () {
var c = $(this).closest('.row').clone();
$(this).after(c);
var count = $(this).closest('.row').find('>.btn-container').length;
//---------------------------------------^^--------------------
alert(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="btn-container col-md-12">
Hello
</div>
</div>
</div>
Rather than find() you could use children(). From jQuery .children() documentation:
The .children() method differs from .find() in that .children() only
travels a single level down the DOM tree while .find() can traverse
down multiple levels to select descendant elements (grandchildren,
etc.) as well
var count = $(this).closest('.row').children('optional-selector').length;
I have several instances of a class in a div. I know the id of the div. I can't get it to work.
$('#ContactPersonChildListDiv').children().filter('.lrml').hide()
This doesn't work.
So I need to hide all the children of the div with id='ContactPersonChildListDiv', that belong to the class lrml.
To hide all the children with that class use > selector:
$('#ContactPersonChildListDiv > .lrml').hide();
If you want to hide all descendants with that class use:
$('#ContactPersonChildListDiv .lrml').hide();
Selecting elements with jQuery is very close (in this case, the same) like you select them with CSS selectors:
E F Matches any F element that is a descendant of an E element. Descendant selectors
E > F Matches any F element that is a child of an element E.
What's your HTML code?
You posted that the id of div is
id='#ContactPersonChildListDiv'
Be sure that # doesn't be in this id, like
<div id='ContactPersonChildListDiv'>
try this:
$('#ContactPersonChildListDiv').children('.lrml').hide();
Fiddle
The HTML:
<div id='ContactPersonChildListDiv'>
<div class='aaa'>AAA</div>
<div class='lrml'>LRML</div>
<div class='bbb'>BBB</div>
</div>
<input type='button' onclick='hideSomeClass()'>
AND JS:
function hideSomeClass(){
var pdiv=document.getElementById('ContactPersonChildListDiv');
var divs=pdiv.children;
for (var i = divs.length - 1; i >= 0; i--) {
if(divs[i].className=='lrml'){
divs[i].style.display='none';
}
};
}
Well, you didn't provide any HTML but this may help you.
Try this:
$('#ContactPersonChildListDiv').find('.lrml').hide();
Youl could also do this way:
$('#ContactPersonChildListDiv .lrml').hide();
<div id="start_123_end"</div>
<div id = "start_123_ok"</div>
<div id="start_123_error"</div>
<div id = "start_123_notstarted"</div>
I want to select a div which start with "start" and ends with "end " or "ok"
Pseduo Code:
vae selected $("div[id^=__w2][id$=_end || _ok]")
as there can be many elements
You can use .filter()
var selected = $("div[id^=start]").filter("[id$=_ok],[id$=_end]");
DEMO
Use start and end selector with comma
$('div[id ^=start][id $=_ok],div[id ^=start][id $=_end ]')
Instead of rather slow attribute selectors, you can use a filter with a regex:
$('div').filter(function() {
return /^start.+(end|ok)$/.test(this.id);
}).addClass('selected');
Example fiddle
I have a list of divs that I need to traverse to return a particular length. I must add up all the total amount of divs that have active images. Inactive images are denoted by an alt= "missing". I need this particular length size for an ajax interactions.
Question
How can I get the length of parent divs, that do NOT have children elements with a alt tag value of missing? (sorry for the verbosity in selectors)
HTML
<div class="project-img-container">
<div class="modal-image-0">
<img alt="Florence" class="featured" src="/system/works/avatars/000/000/034/medium/florence.jpg?1374131286">
</div>
<div class="modal-image-1">
<img alt="Nexus" class="featured" src="/system/works/avatar_bs/000/000/034/medium/nexus.jpg?1374131286">
</div>
<div class="modal-image-2">
<img alt="Missing" class="featured" src="/images/medium/missing.png">
</div>
<div class="modal-image-3">
<img alt="Missing" class="featured" src="/images/medium/missing.png">
</div>
</div>
Jquery success: postImgModal
postImgModal = function(data, status) {
var activeChildren, children, imgVal;
imgVal = [];
children = $(data).find('.project-img-container').children();
/*
children will return an object list of all divs (which in this case = 4) now I must remove the parent tags that have children img tags that have alt tag's value = "missing."
Lets call this var activeChildren
*/
$.each(activeChildren, function(i, child) {
imgVal[i] = child;
console.log(imgVal[i]);
return imgVal[i];
});
/*this loop should return a length of 2. Opposed to before which was 4. This is because there were 2 missing alt tags above in this example html.*/
}
The final output should be a length of 2 for var activeChildren = 2; and imgVal should return just these two divs
<div class="modal-image-0">
<img alt="Florence" class="featured" src="/system/works/avatars/000/000/034/medium/florence.jpg?1374131286">
</div>
<div class="modal-image-1">
<img alt="Nexus" class="featured" src="/system/works/avatar_bs/000/000/034/medium/nexus.jpg?1374131286">
</div>
$(data).find('.project-img-container').children().filter(function() {
return !$(this).find('[alt="Missing"]').length;
});
FIDDLE
or just:
$(data).find('.project-img-container').children(':has([alt!="Missing"])');
I believe this should work
$('div > img:not([alt="Missing"])').length;
Or This one looks for featured images.
$('div > img.featured:not([alt="Missing"])').length;
jQuery property value is case sensitive so you have to make sure it's in the right case:
$(".project-img-container").find("img:not([alt='Missing'])")
You can just use jQuery selectors to meet your needs. Below expression should serve the purpose.
$('div.project-img-container').find('img[alt!="Missing"]').parent();