Check if a child div exists with a specific data attribute in the parent section using jQuery

How to check if a parent has sectionanother “child” divwith a specific data attribute? Here is what I will 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>
Run codeHide result
+4
source share
3 answers

just aim at the item and check if it is there by checking the collections length

Exact match with 1

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

Contains 1

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

Begin with 1

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

Ends on 1

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

You can check the children of elment with a selector >and use [data-attribute selector], than to check if there is a result> 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/

+1

:

$("#parent>div").each(function(){

    if ($(this).attr('data-child-nr') === "1") {
        // div exists           --> yes
        alert('ok');
    }
    else {
        // div doesn't exists   --> no
        alert('nope');
    }
});
0

Source: https://habr.com/ru/post/1620114/


All Articles