Ado
Ado

Reputation: 65

jQuery check if a P tag contains a A tag with a given id

I have the following code I am trying to determine if the P tag contains a A tag with the id = Test1. Thanks you.

HTML:

<div>
    <p id="header"></p>
</div>

jQuery:

$(document).ready(function (e) {
    // Append A tag with id= Test1
    $('#header').append("<a href='#' id='Test1'> Test1</a>")

    // If the p with id = header contains a A tag with id = Test1.
});

Upvotes: 3

Views: 1325

Answers (2)

Vineet
Vineet

Reputation: 4645

Just try

if(!$( "p#header" ).has( "a#Test1" ).length){
   $('#header').append("<a href='#' id='Test1'> Test1</a>")
}else{
   //Your p element has this anchor with id test1
}

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281764

Use the find method to check if the anchor tag with a given id is present.

$(document).ready(function (e) {
    // Append A tag with id= Test1
    $('#header').append("<a href='#' id='Test1'> Test1</a>")

    // If the p with id = header contains a A tag with id = Test1.
    if($('#header').find('a#Test1').length){
      alert('yes');
    }else {
      alert('no');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <p id="header"></p>
</div>

Upvotes: 2

Related Questions