How to hide class in a div - javascript

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();

Related

JavaScript possible to select all elements with classname that starts with (...)? [duplicate]

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.

Jquery assign second child attribute

Is there a way to assign nested div attribute with variable? Like
<div>
<div>
123456
</div>
</div>
Become
<div>
<div sectionid="123">
123456
</div>
</div>
BTW above component will be created by JavaScript.
I've tried something like this, but it didn't work.
var a = $('<div><div>123456</div></div>');
a.eq(":nth-child(2)").attr("sectionid", "123");
Try this snippet.
//FOR DOM HTML
console.log("FOR DOM HTML");
//1st way
$('#input > div').find('div').attr("sectionid","123");
console.log($('#input').html());
//2nd way
$('#input > div > div').attr("sectionid","321");
console.log($('#input').html());
//JS HTML
console.log("FOR JS OBJECT");
var input = $('<div><div>123456</div></div>');
//1st way
input.eq(0).children().attr('sectionid', '456');
console.log(input[0].outerHTML);
var input = $('<div><div>123456</div></div>');
//2nd way
$(input[0]).children().attr('sectionid', '789');
console.log(input[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input">
<div>
<div>
123456
</div>
</div>
</div>
nth-child(2) maches elements that are the second child element of their parent. This is not the case for your div, it is the first element of the parent div.
.eq finds an element at a specific index. It is not the place to pass a selector.
The child selector, >, will find a child element, i.e. div>div will find a div that is an immediate child of a div.
Note that the code you've provided, $('<div></div>123456<div></div>');, doesn't create a DOM tree like the one you've pasted.
Update, now that the code is edited, the value of a is a div with a child div. Since a.find will perform a search within a, you don't have to use a child selector, but can find the div immediately:
a.find('div')
Just apply attribute to children. No complicated 'find', eq(), etc.
var a = $('<div><div>123456</div></div>');
a.children().attr('sectionid', '123');
$('body').append(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Why don't you add it in the first place? Not clear if you add it later!
$(document).ready(function() {
var sectionid = "123";
var a = $('<div><div sectionid="' + sectionid + '">123456</div></div>');
$('body').append(a);
});
div[sectionid]{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this - I have added comments to the code to explain what is happening.
Inspect the element to see that the attribute is added
var a = $('<div><div>123456</div></div>'); // change this to match the structure you want
a.children() // .children gets the direct descendant (which should be the nested div
.eq(0) // gets the first in the array that is returned (if there are multiple direct descendents) - it is a 0 based index selector
.attr('sectionid', '123');
$('body').append(a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
More information about .children()
More information about .eq()
try it :
$(document).ready(function(){
$("div").eq(1).attr("sectionid","123");
})

Siblings with same attribute value

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.

How to check if any div has inner div having specific class say 'xyz' using javascript?

<div class="abc">
<a><img></a>
<h4></h4>
<div class="xyz">
Hello
</div>
</div>
in above html code how do i check whether div having class abc has div having class xyz.
You can simply do this:
var list = document.querySelectorAll('div.abc div.xyz');
if (1 == list.length) {
alert("found");
}
Here's a demo: http://jsfiddle.net/3xQ5X/
Using JQuery:
$("div.abc").has("div.xyz");
Try something like this:
Get your parent div an id like abc.
var v = document.getElementById('abc');
for(var i in v.children)
{
if( v.children[i].nodeName == 'DIV')//this will tell if the parent div has children divs
{
console.log(v.children[i].className == 'xyz');//this will be true if the child div has a class named xyz.
}
}
Also remember to modify this script according to your requirement. I mean you can give an specific class in place of id to the divs you want to traverse. To select all the divs containing some specific class, use this link's function.
This script will do the needful.
<script type="text/javascript">
$(document).ready(function(){
if($("div.abc").children('div').hasClass("xyz"))
{
alert("found");
}
});
</script>

jQuery select if multiple elements has the same class

Example HTML:
<div class="elem-1"></div>
<div class="elem-2"></div>
<div class="elem-2"></div>
<div class="elem-3"></div>
<div class="elem-4"></div>
<div class="elem-4"></div>
<div class="elem-4"></div>
Needed:
How can I select the div's which has "elem-2"s and "elem-4"s with jQuery selectors? (multiple elements has same class)
You can use , to separate different selectors:
$(".elem-2, .elem-4")
selector will be given the value that you desire
http://jsfiddle.net/mMEN5/1
var selector = $();
var list = $('[class]').toArray().reduce(function(p, e){
p = p || {};
var classes = $(e).prop('class').split(/\s/);
$.each(classes, function(i,c){
p[c] = p[c] || [];
p[c].push(e);
});
return p;
}, {})
for (el in list) if (list[el].length > 1) selector=selector.add(list[el]);
​
$('.elem-2, .elem-4').hide() // or any other jquery method
By the way, it's not a jQuery selector, it's just a CSS selector, see this article for an explanation
Even though you have asked for css selector, we can also use the attributeStartsWith selector
I will just mention the selector usage. you can use to for any internal DOM chnage
alert($('div[class^="elem-2"], div[class^="elem-4"]').length);
here i have used .length just to give a correct count. Use can use above with id attributes also.

Categories

Resources