首页 > 解决方案 > 消除

问题描述

I want to print plain text contained in variable my_data within div element with .order_summary_payment class. My first line is an attempt to remove <noscript> tag element, because otherwise its contents are printed with text() method, but <noscript> tag's contents are still in output.

my_data = $('label').not('noscript').text();
$('div.order_summary_payment').text(my_data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>
    mytext
    <img src="https://image-link.com/logo.png" alt="alttext">
    <noscript>
        <img src="https://image-link.com/logo.png" alt="alttext">     
    </noscript>
</label>

标签: jquery

解决方案


.not()只是从集合本身中过滤掉元素,它不会删除子元素。由于您的集合只是元素,因此集合的顶层<label>没有元素,它们嵌套在里面。<noscript>

你需要做的是克隆元素(这样你就不会修改真实的 DOM),然后<noscript>从克隆的 DOM 层次结构中删除元素:

my_elements = $('.wc_payment_methods input:checked').siblings('label').clone();
my_elements.find("noscript").remove();
my_data = my_elements.text();

推荐阅读