简体   繁体   中英

Replace a set of html br elements with another in jQuery — parsing HTML with jQuery

So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

<br><br clear=all><br>

with

<br />

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

Use the Next Adjacent Selector (+) :

$("br+br").remove(); //Removes all <br> tags in front of another

jsFiddle demo

Assuming they are in the exact format you gave, you can do this:

var br = $('br[clear="all"]');
br.attr('clear', '');
br.prev('br').remove();
br.next('br').remove();

You can play with selector attributes, not inside the onload but inside the jquery ready (http://api.jquery.com/ready/)

$('br[clear=all]').remove();

more details on selector attribute:http://api.jquery.com/attribute-equals-selector/

为什么不只替换RSS HTML容器的html:

  yourContainerElem.innerHTML =  yourContainerElem.innerHTML.replace(/<br><br clear=all><br>/gi, '<br />');

To remove all but one:

$('br,[clear!="all"]').remove()

Then to remove the 'clear=all':

$('br').removeAttribute('clear')

You better do this with regexps not with jquery. Simplest example:

string.replace('<br><br clear=all><br>', '<br />')

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