jQuery Tutorial Tutorials - jQuery :has() selector

:has() selector

The jQuery :has() selector is used to select elements which contain another element(s).

jQuery :has() selector Syntax

$(':has()')

jQuery :has() selector Examples

Following is a simple example which makes use of :has Selector.
This would check if the element myDiv has child elements.

<div id="myDiv">
    <p> jquery :has() selector</p>
</div>
<div id="result"></div>
<script>
    if($('#myDiv:has(*)').length){
        $('#result').html('myDiv has child elements');
    }
    else{
        $('#result').html('myDiv has no child elements');
    }
</script>

Try it

In below example,We will hightlight all divs that have a paragraph inside of them.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div><p>Hello</p></div>
<div>Hello again!</div>
<script>
    $("div:has(p)").css('background','cyan');
</script>

Try it

Date:2019-08-18 18:46:08 From:www.Lautturi.com author:Lautturi