猿问

如何使用 jquery 添加或删除所选 li 标记中存在的特定 HTML?

我正在寻找问题的解决方案 - 如何添加或删除所选 li 标记中存在的特定 HTML


我的 HTML 代码是:


<ul id="property-select-list">

<li class="js-property-select" data-id="1" data-has_media_alt="YES">

    prperty1

</li>

<li class="js-property-select selected" data-id="2" data-has_media_alt="NO">

    prperty2

    <div class="tag-indicator"></div>

</li>

<li class="js-property-select" data-id="3" data-has_media_alt="NO">

    prperty3

    <div class="tag-indicator"></div>

</li>

</ul>

如何添加或删除所选 li 标记中存在的特定 HTML。就我而言,具体的 HTML 是<div class="tag-indicator"></div>


请帮助我找到解决方案。


不负相思意
浏览 80回答 2
2回答

扬帆大鱼

// Find correct elementconst el = document.querySelector(".js-property-select.selected");// Create new tag-indicatorconst newElement = document.createElement('div');newElement.className = "tag-indicator";// Append to active elementel.appendChild(newElement);// Optional; remove itconst toRemove = el.querySelector(".tag-indicator");el.removeChild(toRemove);.tag-indicator {height: 10px;border: 1px dotted orange;}<ul id="property-select-list"><li class="js-property-select" data-id="1" data-has_media_alt="YES">&nbsp; &nbsp; prperty1</li><li class="js-property-select selected" data-id="2" data-has_media_alt="NO">&nbsp; &nbsp; prperty2&nbsp; &nbsp; <div class="tag-indicator"></div></li><li class="js-property-select" data-id="3" data-has_media_alt="NO">&nbsp; &nbsp; prperty3&nbsp; &nbsp; <div class="tag-indicator"></div></li></ul>jQuery// Add$('.js-property-select.selected').append('<div class="tag-indicator"></div>');&nbsp;&nbsp;// Optional; Remove$('.js-property-select.selected > .tag-indicator').remove();.tag-indicator {height: 10px;border: 1px dotted orange;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><ul id="property-select-list"><li class="js-property-select" data-id="1" data-has_media_alt="YES">&nbsp; &nbsp; prperty1</li><li class="js-property-select selected" data-id="2" data-has_media_alt="NO">&nbsp; &nbsp; prperty2&nbsp; &nbsp; <div class="tag-indicator"></div></li><li class="js-property-select" data-id="3" data-has_media_alt="NO">&nbsp; &nbsp; prperty3&nbsp; &nbsp; <div class="tag-indicator"></div></li></ul>

Helenr

添加特定的 HTML// Add the html only if it does not exists alreadyif (!$('.js-property-select.selected > .tag-indicator').length) {&nbsp; &nbsp; $('.js-property-select.selected').append('<div class="tag-indicator"></div>');}删除特定的 HTML$('.js-property-select.selected > .tag-indicator').remove();
随时随地看视频慕课网APP

相关分类

Html5
我要回答