jQuery的。将字符串转换为jQuery对象并删除link(a)标记

时间:2022-12-05 16:15:31

I want to remove a href tag from string. From this:

我想从字符串中删除一个href标记。由此:

"google okss strognsstrong"

“google okss strognsstrong”

To this: "google okss strognsstrong"

对此:“google okss strognsstrong”

I already tried:

我已经尝试过:

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

But get error: Cannot read property 'find' of null.

但得到错误:无法读取null的属性'find'。

Maybe somebody knows other approaches?

也许有人知道其他方法?

3 个解决方案

#1


You need to unwrap the contents of the passes selector so

您需要打开传递选择器的内容

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

Demo: Fiddle

#2


Are you sure jQuery is loaded on your page?

你确定你的页面上加载了jQuery吗?

Also, try using .unwrap() (https://api.jquery.com/unwrap/) instead of .remove()

另外,尝试使用.unwrap()(https://api.jquery.com/unwrap/)代替.remove()

#3


Say you have a div that contains your text

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

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

what you can do is use the .text() method that gets the actual text that is included in the #test div and then by using .html() prepopulate the div

你可以做的是使用.text()方法获取#test div中包含的实际文本,然后使用.html()预填充div

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

The above line of code will produce this:

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

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

#1


You need to unwrap the contents of the passes selector so

您需要打开传递选择器的内容

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

Demo: Fiddle

#2


Are you sure jQuery is loaded on your page?

你确定你的页面上加载了jQuery吗?

Also, try using .unwrap() (https://api.jquery.com/unwrap/) instead of .remove()

另外,尝试使用.unwrap()(https://api.jquery.com/unwrap/)代替.remove()

#3


Say you have a div that contains your text

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

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

what you can do is use the .text() method that gets the actual text that is included in the #test div and then by using .html() prepopulate the div

你可以做的是使用.text()方法获取#test div中包含的实际文本,然后使用.html()预填充div

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

The above line of code will produce this:

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

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