1

How can I find the string and wrap it into span using jQuery? For example,

<p>
  <span class="span1">afijaifjiaj</span>
  ajfijaogoag
  <span class="span1">afijaifjiaj</span>
  aokaodgg
  <span class="span1">afijaifjiaj</span>
</p>

I want to make it as:

<p>
  <span class="span1">afijaifjiaj</span>
  <span class="span2">ajfijaogoag</span>
  <span class="span1">afijaifjiaj</span>
  <span class="span2">aokaodgg</span>
  <span class="span1">afijaifjiaj</span>
</p>
1
  • Try using this selector: $('*:contains("I am a simple string")'); Commented Oct 20, 2013 at 22:57

2 Answers 2

2

Try this: http://jsfiddle.net/3nxjk/ or http://jsfiddle.net/3nxjk/3/

nodeType - 3 Represents textual content in an element or attribute.

and $(this).text().trim() trims white space and checks the valid string.

Rest should fit your need :)

Code

$(document).ready(function () {
    $("p").contents().filter(function () {
        return this.nodeType === 3 && $(this).text().trim() != "";
    }).wrap('<span class="span2">');

    alert($('p').html());
});
Sign up to request clarification or add additional context in comments.

3 Comments

what is nodeType === 3 mean?
@Dvir check this out : developer.mozilla.org/en-US/docs/Web/API/… :) The nodeType property returns the node type, as a number, of the specified node.
Depending on cross-browser requirements, it might be worth using $.trim($(this).text()) rather than using String.trim() (it's unsupported in IE < 9).
0

I don't really know jQuery, so here's a way with pure JavaScript:

var stringToReplace='randomtext';
dpcument.body.innerHTML=document.body.innerHTML.replace(stringToReplace,'<span>'+stringToReplace+'</span>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.