简体   繁体   中英

Find a character and then insert HTML tag before it with jQuery

I have some text that display using this markup that I can't change unfortunately

<a class="bt" href="#url">Leadership in Education (29 Oct - 31 Oct 2014)</a>

I'd like to append a <br /> just before the ( so that the date would display on a new line

How do I go about of doing this?

Here's what I've been trying but with no idea how to execute what I'd like to achieve:

http://jsfiddle.net/w6gp2af3/

$("a:contains('(')").html(function () {
    return $(this).html().replace(" (", "<br />("); 
});

jsFiddle example

jQuery selects DOM elements. A bunch of text is not a DOM element, therefore you need to treat it like a string and use string.replace (or regex) to insert the BR where you want it.

You can use jQuery to select the wrapping element. The rest is string manipulation.

You don't want to do this for every a element on your page, so I suggest you add a selector to the code below where appropriate.

The following code uses your selector, and replaces ( with <br>( . Very simple.

$( "a:contains('(')" ).each(function() {
    jQuery(this).html( jQuery(this).html().replace('(', '<br>(') );
});

You can use a regex to replace the open paren with a <br/>( . See fiddle:

http://jsfiddle.net/w6gp2af3/2/

Quick and Easy (this will work for all anchors on your page, so long as they only have one open parenthesis each...):

$( "a:contains('(')" ).css( "text-decoration", "underline" ).each(function(){
    $(this).html($(this).html().replace("(","<br/>("));
});

http://jsfiddle.net/hajx6ffz/

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