简体   繁体   中英

how to get first text node while bypassing <b> and <i>?

I want to get the first text node from a string but it may contain few tags like <b>,<i> and <span> . I have tried it like this but it gives only login whereas it should give login<b>user</b> account

var s = $.trim('login<b>user</b> account<tbody> <tr> <td class="translated">Lorem ipsum dummy text</td></tr><tr><td class="translated">This is a new paragraph</td></tr><tr><td class="translated"><b>Email</b></td></tr><tr><td><i>This is yet another text</i></td> </tr></tbody>');

if( $(s).find('*').andSelf().not('b,i').length > 1 ) {

   if( s.substring( 0, s.indexOf('<') ) != '') {
        alert(s.substring(0, s.indexOf('<')));
    } else {
        alert($(s).find('*:not(:empty)').first().text());
    }
}

check it on jsfiddle

Note:

This string will be dynamic, so write generic answer not specific to this text only.

More Information :

@Jeremy J Starcher! I just want to get the first non-empty text node of iframe being clicked. This node will include <b> or <i> and whatever is in between them like this:

hi my <b>bold</b> text is here // note the bold tags as it is

If only one element is clicked then its text is thrown but if there are more than then one elements selected then it must get the very first text node among all the nodes.

Kind of a brute method but you can take out all the tags you're expecting to occur in the first node and read until the start of the next tag like so:

text = text.replace("<b>"," ");
text = text.replace("</b>"," ");
text = text.replace("<i>"," ");
text = text.replace("</i>"," ");
text = text.replace("<span>"," ");
text = text.replace("</span>"," ");

text = text.substr(0, text.indexOf("<"));

I didn't fully follow the question, but if you are trying to extract the text from a DOM element, this may help:

  var getText = function (el) {
    var ret;
    var txt = [],
      i = 0;

    if (!el) {
      ret = "";
    } else if (el.nodeType === 3) {
      // No problem if it's a text node
      ret = el.nodeValue;
    } else {
      // If there is more to it, then let's gather it all.
      while (el.childNodes[i]) {
        txt[txt.length] = getText(el.childNodes[i]);
        i++;
      }
      // return the array as a string
      ret = txt.join("");
    }
    return ret;
  };

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