简体   繁体   English

jQuery 检查 P 标签是否包含具有给定 id 的 A 标签

[英]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.我有以下代码,我试图确定 P 标签是否包含 id = Test1 的 A 标签。 Thanks you.谢谢。

HTML: HTML:

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

jQuery: 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.
});

Use the find method to check if the anchor tag with a given id is present.使用 find 方法检查具有给定 id 的锚标记是否存在。

 $(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>

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM