JS- Change element class/id based on parent element class - javascript

I'm want to change the class of a child element class based on the parent element class.
For example
<div class="change">
<div class="show-more"></div>
</div>
If parent class is class="change" then change the child class to class="show-none"
<div class="change">
<div class="show-none"></div>
</div>
And how can I also do this to change the child id for example
<div class="change">
<div id="show-more"></div>
</div>
to
<div class="change">
<div id="show-none"></div>
</div>
How can this be done?

You can use CSS selectors and the classlist property.
If you want to do this for one element:
let el = document.querySelector('.change .show-more')
el.classList.remove('show-more')
el.classList.add('show-none')
If you want to do this for all the elements that match this selector:
document.querySelectorAll('.change .show-more').forEach(el => {
el.classList.remove('.show-more')
el.classList.add('show-none')
})

Using Javascript
<div class="change">
<div class="show-more"></div>
</div>
<script>
const allParentElement = document.getElementsByClassName('change');
const child = document.querySelector('.show-more');
for (const parentElement of allParentElement) {
if (parentElement.contains(child)) {
child.classList.add('show-none');
child.classList.remove('show-more');
}
}
</script>

Related

how to add class to element if any of children have specific class in jquery?

how to add class to element if any of children have specific class in jquery?I have a markup
<section class="cc01 cc01v0 cpad" >
<div class="cc01w1 cwidth">
<div class="ocode ocode-initialized">
<div class="ocode-bttn" data-success="Copied to Clipboard" data-error="Error: Could not Copy">
<div>Copy</div>
<div class="ocode-success">Copied to Clipboard</div>
<div class="ocode-error">Error: Could not Copy</div>
</div>
<textarea readonly="readonly" tabindex="-1"></textarea>
</div>
</div>
</section>
.I want to addClass('test') to section element if any of children have ocode class .If any of children have class ocode i want to add class test in the section.
https://jsbin.com/cajavivuru/edit?html,js,output
jQuery(document).ready(function($) {
'use strict';
console.log('cgggggggg11111');
console.log('cgggggggg');
$('.cc01.cc01v0.cpad').each(function () {
console.log('===========');
if($(this).children('ocode').hasClass('ocode')){
$(this).addClass('test')
}
//console.log($(this).css({'background':'red'}))
});
});
By reverse, you can get all elements with .ocode class and
using $().parents() function, you can get all parent elements of that .ocode selector.
And among those parent elements, you can check the tagName of them and for the matched SECTION tagName, add .test class.
jQuery(document).ready(function($) {
$(".ocode").each(function () {
$(this).parents().each(function () {
if($(this).prop("tagName") === "SECTION") {
$(this).addClass("test");
}
});
});
});
<section class="cc01 cc01v0 cpad">
<div class="cc01w1 cwidth">
<div class="ocode ocode-initialized">
<div class="ocode-bttn" data-success="Copied to Clipboard" data-error="Error: Could not Copy">
<div>Copy</div>
<div class="ocode-success">Copied to Clipboard</div>
<div class="ocode-error">Error: Could not Copy</div>
</div>
<textarea readonly="readonly" tabindex="-1"></textarea>
</div>
</div>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

How to retrieve the div first child element sibling node using querySelector?

I have the DOM structure like below
<div class="table_body">
<div class="table_row">
<div class="table_cell">first</div>
<div class="table_cell">chocolate products</div><!-- want to access this div content -->
</div>
<div class="table_row">
<div class="table_cell">third</div>
<div class="table_cell">fourth</div>
</div>
</div>
From the above HTML I want to access the div content of second div with classname table_cell inside first table_row div.
So basically I want to retrieve the content of div with classname table_cell with content chocolate products.
I have tried to do it like below
const element = document.querySelector('.rdt_TableBody');
const element1 = element.querySelectorAll('.rdt_TableRow')[0]
const element2 = element1.querySelectorAll('.rdt_TableCell')[0].innerHTML;
When I log element2 value it gives some strange output and not the text "chocolate products"
Could someone help me how to fix this. Thanks.
You can use:
the :nth-of-type pseudo-selector
combined with the immediate-child selector (>)
Example:
const selectedDiv = document.querySelector('.table_body > div:nth-of-type(1) > div:nth-of-type(2)');
Working Example:
const selectedDiv = document.querySelector('.table_body > div:nth-of-type(1) > div:nth-of-type(2)');
selectedDiv.style.color = 'white';
selectedDiv.style.backgroundColor = 'red';
<div class="table_body">
<div class="table_row">
<div class="table_cell">first</div>
<div class="table_cell">chocolate products</div> //want to access this div content
</div>
<div class="table_row">
<div class="table_cell">third</div>
<div class="table_cell">fourth</div>
</div>
</div>
In your code
element1.querySelectorAll('.table_cell')[0], this is targeting the first element i.e., <div class="table_cell">first</div>. That's the reason why you are not getting the expected output.
I have made it to element1.querySelectorAll('.table_cell')[1], so that it'll target <div class="table_cell">chocolate products</div>.
const element = document.querySelector('.table_body');
const element1 = element.querySelectorAll('.table_row')[0]
const element2 = element1.querySelectorAll('.table_cell')[1].innerHTML;
console.log(element2);
<div class="table_body">
<div class="table_row">
<div class="table_cell">first</div>
<div class="table_cell">chocolate products</div>
</div>
<div class="table_row">
<div class="table_cell">third</div>
<div class="table_cell">fourth</div>
</div>
</div>
Since the element that you want to target is the last div with having class table_cell, you can use :last-of-type on table_cell class using document.querySelector. But otherwise you can also use :nth-of-type if there are more than 2 elements and you want to target any element in between first and last.
Below is the example using :last-of-type.
const elem = document.querySelector(".table_row > .table_cell:last-of-type");
console.log(elem?.innerHTML);
<div class="table_body">
<div class="table_row">
<div class="table_cell">first</div>
<div class="table_cell">chocolate products</div> //want to access this div content
</div>
<div class="table_row">
<div class="table_cell">third</div>
<div class="table_cell">fourth</div>
</div>
</div>
For more info you can refer :nth-of-type, :last-of-type and child combinator(>).

Get Element that Parent not a class

I would like to return an element in javascript that does not have a class in its parent element.
For example, I would like to get the child class element in the following code snippet that does not have 'parent' as a class for the parent element:
<div>
<div class= "parent">
<div class="child">
Not to be selected
</div>
</div>
<div>
<div class="child">
To be selected
</div>
</div>
</div>
I tried to return it through xpath in protractor
You can use the :not selector .
console.log(document.querySelectorAll(':not(.parent) > .child'));
<div>
<div class= "parent">
<div class="child">
Not to be selected
</div>
</div>
<div>
<div class="child">
To be selected
</div>
</div>
</div>
There are a few ways to do this. Either you check if the class is there.
var elementList = [];
document.querySelectorAll("div.child").forEach(function(e) {
var parent = e.parentElement;
if(parent.classList == null || !parent.classList.contains("parent")) {
elementList.push(e);
}
})
console.log(elementList);
If the parent class is specific you can use the css :not attribute
var elementList = document.querySelectorAll("div:not(.parent) > div.child");
console.log(elementList);

find children while moving upwards in dom

This can be sound little confusing but here it is.
What i want is to find the children(OF CLASS PARENT ) when user clicks on class target.
Important: I am not aware of children class & child inside html structure.Target class can be after 'blah' like in first case OR can be directly after children like in second case.
Information available: class "PARENt" and $(this) [class target]
Find: Children(ID) of class PARENT (you cannot use class .children)
<div class="parent">
<div class="children" id="1">
<div class="blah">
<div class="target">TARGET</div>
</div>
</div>
<div class="children" id="2">
<div class="target">TARGET</div>
</div>
<div class="children" id="3">
<div class="blah">
<div class="target">TARGET</div>
</div>
</div>
Example:
Clicking Target 1 would produce: ID = 1
Clicking Target 2 would produce: ID = 2
Clicking Target 3 would produce: ID = 3
If you want to find only ONE ID use:
$('.target').click(function() {
var found = false;
var parent;
var previous;
while(!found) {
if (previous) {
parent = previous.parent();
} else {
parent = $(this).parent();
}
if (parent.hasClass('parent')) {
found = previous;
}
previous = parent;
}
console.log(found.attr('id'));
});
Demo.
To literally answer your question:
$(".parent *") will give you ALL of the children of .parent no matter how many layers deep
To practically answer your question:
Limit possible elements, classes, IDs, etc.
$(".parent div, .parent span, .parent .child ...etc")
You can also grab only the immediate children of an element or set of elements by using the > CSS selector:
$(".parent > *") for example, will give you ALL of the immediate children of .parent
In the context of your problem
$(".target").on("click", function () {
$(this).closest(".parent").children();
// OR
$(this).closest(".parent").find("*");
});
To get the specific ID Given your current DOM structure...
$(".target").on("click", function () {
var id = $(this).closest("[id]").attr("id");
console.log(id);
});
Use .parentsUntil() to get the set of all parents up to (but not including) .parent. Then get the last element of this to get the child of the parent.
$(".target").click(function() {
var child = $(this).parentsUntil(".parent").last();
console.log(child.attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<div class="children" id="1">
<div class="blah">
<div class="target">TARGET</div>
</div>
</div>
<div class="children" id="2">
<div class="target">TARGET</div>
</div>
<div class="children" id="3">
<div class="blah">
<div class="target">TARGET</div>
</div>
</div>
</div>
Another

Getting class name from div

I want to retrieve the class name of the last child element (class last div new3) in .find_class, but my code gives me class select3. How can I fix it?
Demo: http://jsfiddle.net/gBxan/5/
<div class="find_class mediumCell">
<div class="new1 old1">
<div class="select1"></div>
</div>
<div class="new2 old2">
<div class="select2"></div>
</div>
<div class="new3 old3"><!-- I want to get this div's class name 'new3' -->
<div class="select3"></div>
</div>
</div>
var find = $('div.find_class div:last').attr('class');
alert(find);
Use the child selector (>):
var find = $('div.find_class > div:last').attr('class');
Fiddle: http://jsfiddle.net/gBxan/6/
See also: MDN - CSS Selectors
$('.find_class').children(':last').attr('class');

Categories

Resources