Element or its ancestors are member of a class - javascript

How can I check whether an element or any of its ancestors are member of a specific class? As fare as I know, .hasClass only checks for the element itself.
<div class="myClass">
<div>
<div id='myElement'>
</div>
</div>
</div>
<div id = 'notMyElement'>
</div>
$('myElement').anyAncestorHasClass('myClass') == true;
$('notMyElement').anyAncestorHasClass('myClass') == false;

You can check the length of jQuery object returned by .closest() method.
From Documentation:
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
if($('#myElement').closest('.myClass').length) {
document.write('Class Exists');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="myClass">
<div>
<div id='myElement'>
</div>
</div>
</div>
<div id='notMyElement'>
</div>

Related

Javascript changing a specific element in a div

So I have something like this in my html:
<div id="basket">
<div id="item">Apple</div>
</div>
<div id="basket">
<div id="item">Orange</div>
</div>
<div id="basket">
<div id="item">Banana</div>
</div>
// And so on
How would I be able to change the innerHTML of each 'item' div individually?
For example, how would I change the div that says 'banana' to something else?
As already mentioned within the comments, an ID has to be unique so you have to change them to classes.
Then to solve your issue, you can use querySelectorAll to select all elements with the class item. Then you sue the forEach-loop and check the innerHTML of every Element. if it matches "Banana" you can rewrite the innerHTML (should use textContent though for security reasons):
document.querySelectorAll('.item').forEach(el => {
if (el.textContent == 'Banana') {
el.textContent = 'The Minions ate the Banana';
}
})
<div class="basket">
<div class="item">Apple</div>
</div>
<div class="basket">
<div class="item">Orange</div>
</div>
<div class="basket">
<div class="item">Banana</div>
</div>

How to change all classname elements of specific classname

How to change all classname elements of specific classname?
I mean, let's say I have 3 divs with classes "MyClass", and i want to change their classnames to "notMyClass" in JavaScript, how to do it?
<div class="MyClass">
</div>
<div class="MyClass">
</div>
<div class="MyClass">
</div>
<!--TO-->
<div class="notMyClass">
</div>
<div class="notMyClass">
</div>
<div class="notMyClass">
</div>
I know that it's very easy by calling element by it's id, but how to do it by it's classname?
Select all elements with the MyClass class with querySelectorAll, then loop through each element (with NodeList.forEach) and use classList.replace:
document.querySelectorAll('.MyClass').forEach(e => e.classList.replace('MyClass', 'notMyClass'))
.notMyClass{
background-color:green;
}
<div class="MyClass">A</div><div class="MyClass">B</div><div class="MyClass">C</div>
<!--TO-->
<div class="notMyClass">D</div><div class="notMyClass">E</div><div class="notMyClass">F</div>
Use querySelectorAll method:
Array.from(document.querySelectorAll('.MyClass')).forEach(elem => {
elem.className = 'otherClass';
});
Note that I used Array.from, because querySelectorAll returns a NodeList, not an array.

How do I add css property for particular Div if class is found(JQuery)

<div class="b" >
<h1>Hello</h1>
<div class="a">
<p class="ABC">A........Z</p> //this could be present in some pages
</div>
</div>
This is a piece of code in which I want to add css properties to div with class "b" if <p> contains class="ABC".
How to do it?
$("p.ABC").parents("div.b").css('background-color', 'red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b" >
<h1>Hello</h1>
<div class="a">
<p class="ABC">A........Z</p> //this could be present in some pages
</div>
</div>
$("p.ABC") this finds all the p elements has the class ABC.
parents("div.b") finds the first parent that is div and has class named b of the selected element.
css() adds the styles you want. You can also use addClass() method to add predefined class.
Please check if this helps
if($( "p" ).hasClass( "ABC" )) {
// if you want to add a class with many properties, then
$( "div.b" ).addClass( "yourClass" );
// if you want to add one property to existing class then the below statement
$( "div.b" ).css( "attribute-name", value );
}
You can add all the css properties in "yourClass"
if($("p").hasClass("ABC")) {
$("div.b").css("color", "blue");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b" >
<h1>Hello</h1>
<div class="a">
<p class="ABC">A........Z</p> //this could be present in some pages
</div>
</div>
Please check the code snippet.
I added a css property color as blue to the class 'b' if 'p' has 'ABC'. its working
One method is to look directly at <p class="ABC"> and check if it has a class using hasClass(). Then you can traverse upwards to find the nearest element with class="b"
Something like this:
var elementToModify = $('p').hasClass('ABC').closest('.b');
elementToModify.prop('property', newValue);
Checkout these to further understand their use:
prop()
closest()
You can use $("p.ABC") to find all <p> with class ABC then .closest(".b") to find the parent div with class b then .css() to change css properties.
I recommend using .addClass() / .removeClass() rather than change css directly, but this helps you find the parent.
This also allows you to have multiple div class='b' in your html and it will only apply to the one with ABC
$("p.ABC").closest(".b").css("background-color", "pink");
.b+.b {
border-top: 1px solid black;
margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b">
<h1>Hello</h1>
<div class="a">
<p class="ABC">A........Z</p> //this could be present in some pages
</div>
</div>
<div class="b">
<h1>Hello</h1>
<div class="a">
<p class="DEF">ABC not present</p>
</div>
</div>
You can also turn it around using :has
$(".b:has(.ABC)").css("background-color", "pink")
which states: select all .b that has at least one child that has class .ABC, which is nearer to your concept of: add css to div with class "b" if <p> contains class="ABC"
So it depends on which way you want to work it.
$(".b:has(.ABC)").css("background-color", "pink")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b">
<h1>Hello</h1>
<div class="a">
<p class="ABC">A........Z</p> //this could be present in some pages
</div>
</div>
<div class="b">
<h1>Hello</h1>
<div class="a">
<p class="DEF">ABC not present</p>
</div>
</div>

FadeOut all id's with the same name

This is my HTML:
<div class="content-box" id="enabled_add">
<h2 class="title">hallo</h2>
<div class="content-box-heading-orange"></div>
<div class="content-box-content">
Hallo
</div>
</div>
<div class="content-box" id="enabled_add">
<h2 class="title">hallo2</h2>
<div class="content-box-heading-orange"></div>
<div class="content-box-content">
Hallo2
</div>
</div>
This is my JS
$('#usernav_close').click(function(){
setTimeout(function(){
$('#enabled_add').fadeOut('slow');
});
});
I want to get all of the content-boxes with the id enabled_add to FadeOut.
But my problem is that only the first element is selected.
ids must be unique. If you try to reuse an id, only the first will be found/updated by jQuery. You want to use a class here.
<div class="content-box enabled_add">
<h2 class="title">hallo</h2>
<div class="content-box-heading-orange"></div>
<div class="content-box-content">
Hallo
</div>
</div>
<div class="content-box enabled_add">
<h2 class="title">hallo2</h2>
<div class="content-box-heading-orange"></div>
<div class="content-box-content">
Hallo2
</div>
</div>
$('#usernav_close').click(function(){
setTimeout(function(){
$('.enabled_add').fadeOut('slow');
});
});
The id attribute is supposed to be unique to an element on a page. You aren't supposed to use the same id twice in one document.
The difference between ids and classes
You can however give an element more than one class.
<div class="content-box enabled_add">
That would mean your selector would read
$('.enabled_add')

Get elements just 1 level below the current element by javascript

I need to access the DOM tree and get the elements just 1 level below the current element.
Read the following code:
<div id="node">
<div id="a">
<div id="aa">
<div id="ab">
<div id="aba"></div>
</div>
</div>
</div>
<div id="b">
<div id="ba">
<div id="bb">
<div id="bba"></div>
</div>
</div>
</div>
<div id="c">
<div id="ca">
<div id="cb">
<div id="cba"></div>
</div>
</div>
</div>
</div>
I want to get the 3 elements "a", "b", "c" under "node". What should I do?
var nodes = node.getElementsByTagName("div") <---- I get all the divs but not the 3 divs I need.
var nodes = node.childNodes; <---- works in IE, but FF contains Text Node
Does anyone know how to solve the problem?
You could use a function that rules out all non-element nodes:
function getChildNodes(node) {
var children = new Array();
for(var child in node.childNodes) {
if(node.childNodes[child].nodeType == 1) {
children.push(child);
}
}
return children;
}
I'd highly recommend you look at JQuery. The task you're looking to do is straightforward in pure Javascript, but if you're doing any additional DOM traversal, JQuery is going to save you countless hours of frustration. Not only that but it works across all browsers and has a very good "document ready" method.
Your problem solved with JQuery looks like:
$(document).ready(function() {
var children = $("#node").children();
});
It looks for any element with an id of "node" then returns its children. In this case, children is a JQuery collection that can be iterated over using a for loop. Additionally you could iterate over them using the each() command.
This is simplier than you think:
var nodes = node.querySelector("node > div");
Try this (late answer, but can be useful for others):
var list;
list=document.getElementById("node").querySelectorAll("#node>div");
Universal selectors can do the trick:
var subNodes = document.querySelectorAll("#node > *");
Query parts:
#node is unique container selector
> next slector should be applied only on childs
* universal selector that match every tag but not text
Can I use universal selector
In my opinion the easiest way to do this is to add a class name to the
first level child nodes:
<div id="node">
<div id="a" class="level_1">
<div id="aa">
<div id="ab">
<div id="aba"></div>
</div>
</div>
</div>
<div id="b" class="level_1">
<div id="ba">
<div id="bb">
<div id="bba"></div>
</div>
</div>
</div>
<div id="c" class="level_1">
<div id="ca">
<div id="cb">
<div id="cba"></div>
</div>
</div>
</div>
</div>
and then to use the method getElementsByClassName, so in this case:
document.getElementById('node').getElementsByClassName('level_1');
I think node.childNodes is the right place to start. You could (to make it work with FF too), test the nodeName (and possibly nodeType) of all child nodes you get, to skip text nodes.
Also you might have a look at some javascript library like prototype, which provide a lot of useful functions.
I've added some text so we can see that it is working, and JavaScript that will add "added!" to the bottom of each of the divs at the base:
var cDiv = document.querySelectorAll('body > div > div'), i;
for (i = 0; i < cDiv.length; i++)
{
cDiv[i].appendChild(document.createTextNode('added!'));
}
<div id="node">
<div id="a">a
<div id="aa">aa
<div id="ab">ab
<div id="aba">aba</div>
</div>
</div>
</div>
<div id="b">b
<div id="ba">ba
<div id="bb">bb
<div id="bba">bba</div>
</div>
</div>
</div>
<div id="c">c
<div id="ca">ca
<div id="cb">cb
<div id="cba">cba</div>
</div>
</div>
</div>
</div>

Categories