Wrap the first and second word in two different ranges with jQuery

I tried the other two sentences found here to put a space around the word, but each time it led to appearing above the text, not around it.

I have the following code:

<div class="dateCalendar"> June 10 </div> 

I am currently using jQuery:

$ ('. dateCalendar'). html (function (i, v) {return v.replace (/ \ s (. *?) \ s /, '$ 1');});

HTML output shows this:

 <div class="dateCalendar"> <span></span> June 10 </div> 

Ideally, in the end, I would like to wrap the month in between and the date in another run, so that I can put them in css differently.

Some notes that may be helpful in understanding:

  • .dateCalendar will be displayed more than once on the page
  • The date is encoded in PHP in the Wordpress plugin, which I cannot change
+4
source share
3 answers

Try

 $('.dateCalendar').html(function(i, v) { return $.trim(v).replace(/(\w+)/g, '<span>$1</span>'); }); 

Demo: Fiddle

+4
source

How about this - if you take only two words:

Live demo

 $('.dateCalendar').each(function () { var cal = $(this); var texts = $(this).text().split(" "); cal.empty(); $.each(texts,function (i, text) { cal.append('<span class="' + (i == 0 ? "month" : "year") + '" >'+text+'</span>'); }); }); 
+1
source

You are almost there. The reason this happens is because the received content is not wrapped inside any tag.

See http://jsfiddle.net/ZymGK/1/ . This basically returns an array of span elements for each "word" (separated by spaces) and makes the contents of each div element a .dateCalendar class.

0
source

Source: https://habr.com/ru/post/1496429/


All Articles