samba samba - 6 months ago 13
jQuery Question

jQuery don't select a tag in p tag

Hello I try to style numbers in p-tag different and prevent the styling within the a-tag. jQuery adds span-tag called number to the p-tag but should not add this within the href of a-tag.

<div class="ce_text">
<p>1234 example <a class="link" href="http://www.abc.de/123/def" target="_blank">www.abc.de/123/def</a> goes on 567.</p>
<a href="http://www.999.com">Link 999 (no function)</a>
<p>1234 example <a class="link" href="http://www.abc.de/123/def" target="_blank">www.abc.de/123/def</a> goes on 567.</p>
</div>


The number in the p-tag should contain a span-tag, the a-tag should not:

RIGHT: <p><span="number">123</span>text goes here.</p>

WRONG: <a href="http://www.abc.de/<span class="number"123">123<span>/def">link</a>


My approach won't work.

My fiddle:
https://jsfiddle.net/huppen/7f1ccvy5/6/

Any tipps to solve my problem are appreciated.

Problem solved with the approach from Rejith R Krishnan (THANKS!):

$(".ce_text p").contents().filter(function(){
return this.nodeType == 3; //nodeType 3 is the text nodes
}).each(function(i, v) {
$(this).replaceWith(function(){
return this.nodeValue.replace(/(\d+)/g, '<span class="number">$1</span>')
});
});


Working JS-Fiddle

Answer

You can use this approach. Using contents() and filter() select the text nodes in the element, then replaces them with new HTML.

$(".ce_text p").contents().filter(function(){ 
  return this.nodeType == 3; //nodeType 3 is the text nodes
}).each(function(i, v) {
    $(this).replaceWith(function(){
      return this.nodeValue.replace(/(\d+)/g, '<span class="number">$1</span>')
    });
});

DEMO