简体   繁体   中英

Querying a string for an element in jQuery

I have an ajax request that POST s text to another PHP page, which renders it to markdown and sends it back. An example looks like this:

"<p>Meep, meep, <em>meep!!!</em></p>
<pre><code class="language-javascript">var foo = "bar";</code></pre>"

Now, if I wanted to find all elements with the selector pre code , how would I do that? I tried $(text).find("pre code") but with no results given back. What is the problem and how is it done right?

You can use .parseHTML() like this

$('<output>').append($.parseHTML(str)).find('pre code')

 var str = '<p>Meep, meep, <em>meep!!!</em></p>\\ <pre><code class="language-javascript">var foo = "bar"\\ ;</code></pre>'; alert($('<output>').append($.parseHTML(str)).find('pre code').html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Turns out the answer was .filter() .

The text used in the original question is represented as the root area for jQuery - so .filter() has to be used - it returns a list of all the filtered elements. On that, I had to use .find() and got the desired result.

I needed to run hightlight.js over the returned output, here is what it looks like:

$html = $(data);
$html.filter("pre").find("code").each(function(i, block) {
    hljs.highlightBlock(block);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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