Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add child element after checking if child with specific value already exists in JS/JQuery?

So I’ve been trying to figure out, how to append a div element to an existing div element, after checking if the child div element contains a specific text or not in JS/JQuery.

My HTML:

<div id="mii">
</div>

My JQuery:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(document).ready(function () {
    $("#mii").click(function() {
        if($("#mii div span:contains('foo')") == false) {
            $("#mii").append("<div class='mii-item'><span>foo</span></div>");
        }
    });
});

My CSS (Not rly relevant tho):

#mii {
  background-color: gray;
  width: 100%;
  height: 100%;
  padding: 5px;
}
#mii:hover {
  cursor: pointer;
}

.mii-item {
  background-color: yellow;
  padding: 5px;
}

I can’t understand why it doesn’t work, even though I debugged it and tried various things, so any help is welcomed!

Link to JSFiddle

>Solution :

JQuery selector will return a array like of DOM element.
See the output by console.log($("#mii div span:contains('foo')")).
So you need to check the length of array if it contains matched elements.

$(document).ready(function () {
    $("#mii").click(function() {
        if($("#mii div span:contains('foo')").length === 0) {
            $("#mii").append("<div class='mii-item'><span>foo</span></div>");
        }
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading