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:
$(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>");
}
});
});