[英]how to remove an element in html string with jQuery
I have a Html String and I want to parse it to html and then remove any pre
tags and it's children. 我有一个HTML字符串,我想将其解析为html,然后删除所有
pre
标签,它是子标签。 I tried this: 我尝试了这个:
HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></pre>";
var $jQueryObject = $($.parseHTML(HTMLString));
alert($jQueryObject.find('pre').length);
but this alert me 0 that means it can't find any pre
tag. 但这提醒我0,表示找不到任何
pre
标签。 can anyone tell me what's wrong with my code? 谁能告诉我我的代码出了什么问题?
HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></pre>"; var $jQueryObject = $($.parseHTML(HTMLString)); alert($jQueryObject.find('pre').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></pre>"; var $jQueryObject = $("<div/>").html(HTMLString); console.log("Befor Remove tag: "+ $jQueryObject.find('pre').length); $jQueryObject.find('pre').remove(); console.log("After Remove tag: "+ $jQueryObject.find('pre').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
It's not working because <pre>
is in root level of the string. 它不起作用,因为
<pre>
在字符串的根目录下。 For that case filter()
works but it would not find another <pre>
if it was nested inside another of your elements 对于这种情况,
filter()
可以工作,但是如果它嵌套在另一个元素内,它将找不到另一个<pre>
Typically you want to insert the string into another container and use find()
on that other container so you don't need to worry about nesting levels. 通常,您要将字符串插入另一个容器中,并在另一个容器上使用
find()
,因此您不必担心嵌套级别。
HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></pre>"; //changing your code to use `filter()` var $jQueryObject = $($.parseHTML(HTMLString)); console.log('Filter length:', $jQueryObject.filter('pre').length) // Using `find()` within another container var $container = $('<div>').append(HTMLString); console.log('Find length:', $container.find('pre').length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
You need to create a DOM tree using your HTML string by appending to a DOM element, then you can use find()
to get the pre
tag element. 您需要通过将HTML字符串附加到DOM元素来创建DOM树,然后可以使用
find()
获取pre
标签元素。
var HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></pre>"; var $jQueryObject = $('<div>').append($(HTMLString)); console.log($jQueryObject.find('pre').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.