Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if child div with specific data attribute exists in parent section using JQuery

Tags:

html

jquery

How can I check if a parent section has another 'child' div with a specific data attribute? Here is something I'll to do:

if ($("#parent").children().data("child-nr").contains("1") == true) {
    $("#parent").css('background-color', 'green');
}
else {
    $("#parent").css('background-color', 'red');
}
div {
  width: 50px;
  height: 50px;
  background-color: lightblue;
  float: left;
  margin: 5px;
  text-align: center;
  vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<section id="parent">
    <div data-child-nr="1"><p>N° 1</p></div>
    <div data-child-nr="2"><p>N° 2</p></div>
    <div data-child-nr="3"><p>N° 3</p></div>
</section>
like image 582
H. Pauwelyn Avatar asked Feb 08 '23 07:02

H. Pauwelyn


2 Answers

just target the element, and check if it's there by checking the collections length

Exact match to 1

if ( $('#parent div[data-child-nr="1"]').length ) { ...

Contains 1

if ( $('#parent div[data-child-nr*="1"]').length ) { ...

Starts with 1

if ( $('#parent div[data-child-nr^="1"]').length ) { ...

Ends with 1

if ( $('#parent div[data-child-nr$="1"]').length ) { ...
like image 118
adeneo Avatar answered Feb 10 '23 19:02

adeneo


You can check the elment direct children using > selector and use a [data-attribute selector], than check if the result is > 0 like:

Code:

if ($('#parent>div[data-child-nr="1"]').length > 0) {
    // div exists           --> yes
    alert('ok')
}
else {
    // div doesn't exists   --> no
    alert('nope')
}

Demo: http://jsfiddle.net/xt80p2b0/

like image 22
Irvin Dominin Avatar answered Feb 10 '23 19:02

Irvin Dominin