繁体   English   中英

如何使用 Javascript 或 JQuery 替换 HTML 标签,而不使用任何 Class 名称或

[英]How to replace HTML Tags using Javascript or JQuery without any Class name or ID

请帮我更换下面的 html 代码

原始代码

<div class="multiAttType">
    <input type="radio" id="Radio7_1" value="Google">
    <label for="Radio7_1" class="radioChoice">Google</label>
</div>

<div class="multiAttType">
    <input type="radio" id="Radio7_2" value="Bing">
    <label for="Radio7_2" class="radioChoice">Bing</label>
</div>

在 PageLoad 上它应该更改为

<div class="multiAttType">
    <input type="radio" id="Radio7_1" value="Google">
    <span class="sameclass">Google <a href="https://www.google.com/">Link 1</a></span>
</div>

<div class="multiAttType">
    <input type="radio" id="Radio7_2" value="Bing">
    <span class="sameclass">Bing <a href="https://www.bing.com/">Link 2</a></span>
</div>

您可以使用 jquery 中的:contains() 选择器来实现此目的。

示例:$('label:contains("Google")')

现在使用 jquery 中的 replaceWith function 替换 html 内容。

更新了代码片段以替换页面加载时的 html 内容。

 function replaceHtml(){ $('label:contains("Google")').replaceWith('<span class="sameclass">Google <a href="https://www.google.com/">Link 1</a></span>') $('label:contains("Bing")').replaceWith('<span class="sameclass">Bing <a href="https://www.bing.com/">Link 2</a></span>') } $(document).ready(function(){ //calling the replace function on page load replaceHtml(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="multiAttType"> <input type="radio" id="Radio7_1" value="Google"> <label for="Radio7_1" class="radioChoice">Google</label> </div> <div class="multiAttType"> <input type="radio" id="Radio7_2" value="Bing"> <label for="Radio7_2" class="radioChoice">Bing</label> </div> <button onclick="replaceHtml()">Replace</button>

这是 static 方式

 window.onload = function() { var multAtt = document.getElementsByClassName('multiAttType'); for (var i = 0; i < multAtt.length; i++) { var children = multAtt[i].children; for (var j = 0; j < children.length; j++) { if(children[j].innerHTML == 'Google' && children[j].tagName == 'LABEL') { multAtt[i].removeChild(multAtt[i].children[j]); multAtt[i].insertAdjacentHTML('afterend', '<span class="sameclass">Google <a href="https://www.google.com/">Link 1</a></span>'); } else if ( children[j].innerHTML == 'Bing' && children[j].tagName == 'LABEL') { multAtt[i].removeChild(multAtt[i].children[j]); multAtt[i].insertAdjacentHTML('afterend', '<span class="sameclass">Bing <a href="https://www.bing.com/">Link 2</a></span>'); } } } }
 <div class="multiAttType"> <input type="radio" id="Radio7_1" value="Google"> <label for="Radio7_1" class="radioChoice">Google</label> </div> <div class="multiAttType"> <input type="radio" id="Radio7_2" value="Bing"> <label for="Radio7_2" class="radioChoice">Bing</label> </div>

暂无
暂无

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

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