On one of my web pages I'm currently checking whether a css class isn't being used, like so:
if (!$('*').hasClass("my-special-class")) {
The above works but it's checking every element on the page. In fact, I only need to check within a particular div
(id = 'mydiv') and its child elements, but am not quite sure what sort of selector to use, and would welcome a suggestion?
All you need to do is use the selector itself to compare in an if
statement
if($('.my-special-class').length > 0){
//element with this class exists - do something
}
This will search the DOM for any element with the class my-special-class
. If it cannot find that element, then the length is returned as 0
Alternatively you can modify your selector if you want to find it within a certain element -
if($('#myDiv .my-special-class').length > 0){
//element exists in #myDiv - do something
}
This selector works the same way that any CSS selector works, any children of myDiv
with the class my-special-class
will be selected
use
$('#myID').find(".my-special-class").length
It will return 0, if there are no elements with that class inside that parent div.
if ( $('#yourIDorClass').children().length > 0 ) {
// do something
}
This should work. The children() function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.
you have to use like this
$('#mydiv *').hasClass("my-special-class")
It will return true if the class is being used by any of the child elements of mydiv,false if not used.
$('#myDiv .my-special-class').length
Should do the job :-)
The reason that it is checking everything on your HTML page for that class is because you are using '*'
in your jQuery selector.
If you want to target a specific div with jQuery just alter your code to look like:
if (!$('#myDiv').hasClass("my-special-class")) {
...
}
I'm not able to pass the state value to the method or function in React [closed]
How to access array index of Cloud Firestore using query in Flutter?
Getting an unwanted space between Nav Items in Navbar Angular
PHP Script INSERT INTO SELECT does not insert, with no errors [closed]
SQL query to select students who have taken all subjects from subjects table
Displaying Dynamic placeholder content on Textbox in ReactJS
Extracting Parameters from Redirect URI - QuickBooks API / Python
I am trying to add a small delay (2 sec) between the loader icon and the success with the data as html. .
What I'm trying to do is including multiple php files in my page put I want to load php files only when I click the related tab.
I want to show in an iframe a webpage (an external url), and then show all the code JS requested by this iframe in a textarea. .