jQuery。将字符串转换为 jQuery 对象并移除 link (a) 标签

jQuery. Convert string to jQuery object and remove link (a) tag

我想从字符串中删除一个 href 标签。 来自:

"google 好强"

为此:"google okss strognsstrong"

我已经试过了:

function removeElements(text, selector) {
    var wrapped = $("<div>" + text + "</div>");
    wrapped.find(selector).remove();
    return wrapped.html();
}
var newContent = removeElements(tinyMCE.get('opt3').getContent(), 'a');

但出现错误:无法读取 属性 'find' of null.

也许有人知道其他方法?

您确定 jQuery 已加载到您的页面上吗?

此外,尝试使用 .unwrap() (https://api.jquery.com/unwrap/) 而不是 .remove()

假设您有一个 div 包含您的文字

<div class="test">
   <a id="link" href="http://www.google.com">google</a> " okss strognsstrong
</div>

您可以使用 .text() method that gets the actual text that is included in the #test div and then by using .html() 预填充 div

$("#test").html($('#test').text());

上面的代码行将产生这个:

<div class="test">
    google okss strognsstrong
</div>

您需要 unwrap the contents 通行证选择器

function removeElements(text, selector) {
    var wrapped = $("<div>/", {
        html: text
    });
    wrapped.find(selector).contents().unwrap();
    return wrapped.html();
}

演示:Fiddle