简体   繁体   中英

JavaScript replace method disables line breaks

I have a div with id #container , this div contains couple of strings/lines. I use the below code to hide a specific string inside that div.

$('div#container').text(function (i, t) {
    return t.replace('Some text to be hidden', '');
})

The problem is: by adding the above code, all other strings/lines in the div become joined together. ie line breaks are disabled. If I removed the code, the line breaks works fine.

How can I hide that specific string without disabling line breaks?

I tried to put \\n like this: return t.replace('Some text to be hidden', '\\n'); but that didn't help.

Any suggestions? Answers are greatly appreciated. Thank you.

You need to do your search and replace on individual text nodes so you don't destroy the other child elements (like <br> or <p> tags) .

If the text nodes are immediate children of the #container object, then you can do that like this:

$('#container').contents().filter(function() {
  return this.nodeType === 3;
}).each(function() {
    this.nodeValue = this.nodeValue.replace('Some text to be hidden', '');
});

If the text nodes are deeper children, then we could only offer a simple answer if you show us the actual HTML you're working with.

You can try this by using display none css http://jsfiddle.net/gShM4/67/

<div class="text">Good Stuff Some text to be hidden</br> above element is hide  </div>

$('div.text').html(function (i, t) {
    return t.replace('Some text to be hidden', '<span class="hidden"></span>');
})

.hidden {
    display:none;
}

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