开发者

Need to extract a specific text node to hide or remove it using JQuery

I have a blog on WordPress that I have control over in 开发者_如何学编程order to edit and format the RSS feed content. I have another website on which I want to display the excerpts of the posts from my blog, then link to the blog directly for the full post. The feed I am getting is fine except I have some unwanted untagged text displaying, and because it has no HTML tags I can't use CSS to hide it. (I appreciate that I also need to debug the feed and probably the blog content, as the feed code I'm using doesn't give this error on any other blogs I've set up, but that's a separate issue).

This is the format of the HTML that is being generated from the feed:

        <li class="rss-item">
      <a class="rss-item" href="http://myblog.com/post-title">Post Title</a>
      <br>
      http://myblog.com/post-title/Post Title <!-- this line I want to remove -->
      <div class="thumbnail">
        <a href="#">
        <img src="thumbnail.jpg">
        </a>
      </div>
      <div class="excerpt">Excerpt text</div>
      <a href="http://myblog.com/post-title">Continue reading...</a>
    </li>

I wish to extract the text node for the untagged text (which displays the URL and Post Title on the page) and either remove it using JQuery, or add some span tags and hide it using CSS. My JQuery knowledge is very limited, and I have tried to edit various bits of code I've found online without success. Can anyone help?


var tn = $('a.rss-item[href="http://myblog.com/post-title"] + br')[0].nextSibling;

tn.parentNode.removeChild( tn );

Example: http://jsfiddle.net/BZ5Tx/

This finds the br element whose previous sibling is the a element with the rss-item class and the href http://myblog.com/post-title.

Then it extracts the DOM element, gets the nextSibling which should be the text node, and stores it in a variable.

Then from the text node, get the parentNode and use removeChild to remove the text node.


If this is a repeating pattern with different urls, you can try this selector instead:

$('a.rss-item[href] + br');

...and use a loop:

$('a.rss-item[href] + br').each(function() {

    var tn = this.nextSibling;

    tn.parentNode.removeChild( tn );

});

As noted by @Anurag, it's a good idea to do a loop at each location, removing text nodes until a non text node is reached, just in case there are adjacent text nodes.

$('a.rss-item[href] + br').each(function() {

    var tn = this;

    while( tn = tn.nextSibling  ) {
        if( tn.nodeType === 3 ) {
            tn.parentNode.removeChild( tn );
        }
    }

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜