jQuery DOM parser?

2019-08-20 02:30发布

I've got a jQuery script that calls out to the Yahoo Boss API and retrieves a list of keywords related to a seed keyword phrase. Once the script has the keyword list, I'm then writing these keywords to the screen, each in a span tag to allow the user to add them to their post/page content (WordPress)

The script is working great and now I'd like to enhance it a bit so that I can highlight a keyword in the listing if it already appears inside the content being edited.

What I need to do is to parse the contents of a textarea (the WordPress content editor) and for every matching term that exists in the content, I need to apply a special style to the keyword's span tag in the LSI list.

I'm looking for your suggestions on resources or examples on using javascript and jQuery to parse the innerText (aka content sans html tags) content of the WordPress content editor.

For example, I have a button which when clicked, executes the following jQuery which pulls a listing of keywords, then adds them to a string "result" to write them to the screen...

for (key in keywords){if (keywords[key] > 5) result += '<span>' + key + ',</span>';}

So what I need to do is to evaluate, for each keyword returned inside the loop, if it appears in the content editor (jQuery('#content').html()) and if so, I need to add a highlight class to the span. Otherwise, leave it as is.

2条回答
爷、活的狠高调
2楼-- · 2019-08-20 02:56

Given the contents as an HTML string, here would be one case-sensitive way to do it, with filled-in example variables shown above the meat of the function.

var content = "<div>But this is a div!</div><p>This is a paragraph.  Do you like this paragraph?</p>";

// append to a div to make sure there's a top-level tag.
var html = $("<div></div>").append(content).html();

// keywordList is a selector for a div containing spans of items representing the contents
$("#keywordList").find("span").filter(function() {
    return html.indexOf($(this).html()) != -1;
}).each(function() {
    $(this).html("<span class='highlight'>" + $(this).html() + "</span>");
});

Here's the test HTML:

<div id="keywordList">
    <span>paragraph</span><br />
    <span>span</span><br />
    <span>ul</span><br />
    <span>div</span><br />
    <span>ol</span><br />
    <span>table</span><br />
</div>

You can see this in action.

查看更多
你好瞎i
3楼-- · 2019-08-20 03:01

The content text area may be getting converted to iframe dynamically for advanced editing features and you may need to grab and manipulate the iframe content using the contents function in jquery. Use firebug to find out what the actual tag of content text area converted to.

查看更多
登录 后发表回答