Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
});
like image 940
Ado Avatar asked Feb 02 '26 19:02

Ado


2 Answers

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>
like image 104
Shubham Khatri Avatar answered Feb 04 '26 09:02

Shubham Khatri


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
}
like image 42
Vineet Avatar answered Feb 04 '26 08:02

Vineet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!