Removing text from inside a <div> [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove text with jQuery
I want to remove the text from a div, but that div contains other nodes.
If i use $("#hwiTestimonial").text(""); it erases the <br/> and the <div> as well. How can I only specify to remove the text, without any nodes?
<div id="hwiTestimonial">
" Bla bla"
<br/>
<div>....</div>
</div>

You can filter the contents of the element to leave only text nodes:
$("#hwiTestimonial").contents().filter(function () {
return this.nodeType === 3; // Text nodes only
}).remove();
Here's a working example.

you can use any one of these
$("#hwiTestimonial")
.contents()
.filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).remove();
or you can use this for old browser support also
$("#hwiTestimonial").contents().filter(function () {
return this.nodeType === 3; // Text nodes only
}).remove();

Related

iterate in parent element and get text nodes [duplicate]

This question already has answers here:
How to get the text node of an element?
(11 answers)
Closed 6 months ago.
I am trying to learn DOM scrapping using jquery. I have a structure like this
<p>
A. liver.
<br> B. diaphragm.
<br> C. esophagus.
<br> D. pancreas.
</p>
How can I iterate in this P tag and get TEXT NODES in an array,, e.g [A-Text,BText,CText,DText], I do not want <br> tag.
Please help I could not figure it out, how to loop in P tag childs and segregate text nodes.
Thanks
To do this using jQuery you can use a combination of contents() to get all the nodes within the parent, then filter() to get the textNodes only. Try this:
var textNodeArray = $('p').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE && this.textContent.trim();
}).get();
/* for demo purposes */
textNodeArray.forEach(function(node) {
console.log(node.textContent.trim());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
A. liver.
<br>B. diaphragm.
<br>C. esophagus.
<br>D. pancreas.
</p>
The solution using .contents(), .filter() and .map() functions:
var textNodes = $('p').contents().filter(function(){
return this.nodeType === 3;
}).map(function(i, n){
return n.nodeValue.trim();
}).get();
console.log(textNodes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
A. liver.
<br> B. diaphragm.
<br> C. esophagus.
<br> D. pancreas.
</p>
You can use contents function to get the children of the p element (including text and comment nodes) and then use filter to reduce collection to only nodes of text type.
var arr = [];
var getTextNodesContent = function(el) {
return $(el).children().addBack().contents().filter(function() {
var isTextNode = this.nodeType == 3;
if (isTextNode) {
arr.push($(this).text().trim())
}
return this.nodeType == 3;
});
};
getTextNodesContent($('p'))
console.log(arr);

Changing text with Jquery after a Div [duplicate]

This question already has answers here:
How do I select text nodes with jQuery?
(12 answers)
Closed 8 years ago.
Is it possible to use JQuery to hide the input elements plus the text after the input? The code is generated, so I cannot change the text, wrap it in a span or alter it in any way.
<label>Event Location <span class="req">*</span></label><br>
<input type="radio" name="a22" id="a22_0" value="Lafayette LA">Lafayette LA<br>
<input type="radio" name="a22" id="a22_1" value="Houston TX">Houston TX<br>
<input type="radio" name="a22" id="a22_3" value="San Antonio TX">San Antonio TX
You need to iterate the parent elements (TDs in your example added as an answer), find all the text elements that follow a radio button, then wrap them in hidden spans:
e.g.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6gzfLorp/3/
$('td').contents().each(function (e) {
if (this.nodeType == 3 && $(this).prevAll(':radio').length) {
$(this).wrap($('<span>').hide());
}
});
Note: Your question is a little ambiguous, but it would appear from your answer you have TDs which you could just hide all contents of the TD using:
http://jsfiddle.net/TrueBlueAussie/6gzfLorp/7/
$('.set-cities td').each(function (e) {
$(this).contents().wrapAll($('<span>').hide());
});
It is wrapped in a td tag. Here's what I have for now:
$("label:contains('Event Location')").parent("td").wrap("<span class='set-cities'></span>");
$('.set-cities').empty();
$('.set-cities').append("<td><label>Event Location <span class='req'>*</span></label><br><input type='radio' name='aa2' id='aa2_1' value='Houston TX' checked='checked'>Houston TX<br></td>");
I just going to change the whole block of text rather than just the city name.
In case you wanted to replace the text node directly, here's a way to do it. I borrowed from https://stackoverflow.com/a/298758/728393 and tailored it to your situation
function replaceTextAfter(selector,newtext){
var textnode = $(selector).parent().contents() // we need to contents as a collection
.filter(function(){
return this.nodeType == 3 && $(this).prev().is($(selector)); //return true if node is text and the previous node is our selector
});
textnode[0].data = newtext; //change the text
}
replaceTextAfter('#a22_0','abc');
http://jsfiddle.net/z606no23/
Thi delete all text after an element done, until a new tag
http://jsfiddle.net/alemarch/hm7ey6t5/
function deleteElemPlusText( elem ) {
var contestoHtml = $(elem).parent().html()
var thisHtml = $(elem).get(0).outerHTML // $(elem).outerHTML()
var re = new RegExp(thisHtml + "([^<])*")
var newContesto = contestoHtml.replace(re, "")
$(elem).parent().html(newContesto)
}
function deleteAllElemsPlusText( toDelete ) {
var x = $(toDelete).length;
for (var i = 0; i < x; i++) {
deleteElemPlusText($(toDelete).eq(0))
}
}
deleteAllElemsPlusText( "input[type=radio]" )
note: not all browser have outerHTML properties access, but you can use this jquery plugin http://www.darlesson.com/jquery/outerhtml/

How to safetly replace the value after the "td" tag? (In JQuery) [duplicate]

This question already has answers here:
How can I change an element's text without changing its child elements?
(16 answers)
Closed 9 years ago.
Inside the "td" tag, how do I replace the "BMW" word after the "span" tag without removing the whole "span" tag script? (In JQuery).
The word "BMW" is wildcard wording. It can be "Ford", "Volvo", etc.
I'm using JQuery version 2.0
$('#'....).???
<td>
<span column="17" style="cursor:pointer"></span> BMW
</td>
Just use nextSibling if the text node is the next sibling like in the question:
$('span[column="17"]').get(0).nextSibling.nodeValue = 'Volvo';
FIDDLE
Try this out... Note that I'm omitting any text nodes that are whitespace:
$("YOUR TD SELECTOR HERE")
.contents()
.filter(
function() {
return this.nodeType == 3 && $(this).text().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
)
.text('text to replace here');
You can use .contents(), .filter(), and .replaceWith():
EXAMPLE:
$('table').find('td')
.contents()
.filter(function() {
return this.nodeType === 3;
})
.replaceWith("hello world");
});
http://jsfiddle.net/V4wF5/1/
Edit: I forgot the closing end parenthesis for the first call.
Not sure how you are identifying the column so you may need to change the selector. This is a straight search and replace. You did want to only replace the word BMW, correct?
// Example: $(table.cars td)
$('td').each(function()
{
var repl = $(this).html().replace('BMW', 'Ford');
$(this).html(repl);
});
I do not know any nice jQuery solution, so I provide low level javaScript way. Sorry for that, but believe it helps.
$("td").each(function(i,v){
for (var i = 0;i < v.childNodes.length;i++){
if (v.childNodes[i].constructor.name=="Text"){
v.childNodes[i].nodeValue=v.childNodes[i].nodeValue.replace(/BMW/,"Volvo");
}
}
});
Edit:
It's little bin incompatible so it's better version:
$("td").each(function(i,v){
for (var i = 0;i < v.childNodes.length;i++){
if (v.childNodes[i] instanceof Text){
v.childNodes[i].nodeValue=v.childNodes[i].nodeValue.replace(/BMW/,"Volvo");
}
}
});
Here I bring it to life: http://jsbin.com/ItotOPo/1/edit?html,js,output

How to change html div without affecting inner divs in JQuery [duplicate]

This question already has answers here:
JQuery change inner text but preserve html
(14 answers)
Closed 9 years ago.
How can I change html inside a Div in HTML without affecting inner divs inside the parent div in Jquery.
So far I have this:
HTML:
<div id="div_to_change">
This is the text
<br>
to be changed
<div id="div_that_shouldnt_change">
text that should not change
</div>
<div id="div_that_shouldnt_change2">
text that should not change
</div>
</div>
JQUERY:
$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("changed text");
The only problem is that it works fine if there are no tags on the html, but for example it doesn't change after the <br> or <strong> etc.
JSFIDDLE HERE
One way:
$('#div_to_change').contents().each(function () {
//select only nodes with type 3 and having a node value to ignore empty lines, format chars etc
if(this.nodeType == 3
&& $.trim(this.nodeValue)
)
{
$(this).replaceWith("changed text")
}
});
Demo
Or Just with the filter:
$('#div_to_change').contents().filter(function () {
return (this.nodeType == 3
&& $.trim(this.nodeValue)
)
}).replaceWith("changed text");
Demo

In jquery, how can I detect if a paragraph contains one link and only one link, nothing else

I want to apply a class 'solo' to a link in a paragraph where that link is the ONLY element in the paragraph.
So this would get the 'solo' class:
<p><a>I am alone</a></p>
But this would not:
<p><a>I am not alone</a> because there is more text!</p>
You could do:
$('p').filter(function() {
var $childNodes = $(this).contents();
return $childNodes
.not($childNodes.filter('a').first())
.not(function() {
return this.nodeType === 3 && $.trim(this.nodeValue) === '';
}).length === 0;
});
This gets all child nodes (including text nodes) and removes the first a element it finds and all text nodes only containing whitespaces from that set. If the resulting set is empty, the link was the only child (alone).
Reference: filter, not, contents, Node.nodeType, trim
Update: Maybe this could be done easier, but I wanted it to work also for the case your HTML contains line breaks, which would result in text nodes containing only whitespaces:
<p>
<a>I am alone</a>
</p>
<p>
<a>I am not alone</a> because there is more text!
</p>
DEMO
Try this
$('p').filter(function(){
var $childrens = $(this).children();
return ($childrens.length == 1
&& $childrens.is('a')
&& $(this).text() == $childrens.text());
}).addClass('solo');
Demo
There is 1 more way to do this:
if($("p").find('a').length === 1){
//perform operation
}
Not very performant, but this is the most concise and nice (and working) solution I came out with!
$('p').filter( function() {
return !$('<p>'+$.trim($(this).html())+'</p>').contents().not('a:first').length;
}).addClass('solo');
http://jsfiddle.net/DYxgu/

Categories