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
Related
This question already has answers here:
How do I check if string contains substring? [duplicate]
(12 answers)
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 11 months ago.
I am trying to hide a div if another div contains a specific word.
This is my HTML
<div class="dynamic">
This text is hidden if another div contains the word "download"
</div>
<div class="something">
<div class="btn-download">
If this text has the word "download" the div with class "dynmaic" is hidden
</div>
</div>
JS
jQuery(document).ready(function($){
if ( $('.btn-download').text() === 'download' ) {
$('.dynamic').hide();
}
});
What am I doing wrong? And do I need jQuery for it?
JSFiddle
many many thanks in advance
If a text in div contain a specific word you can use includes method on string ($(selector).text().includes('your-text-search'))
if ( $('.btn-download').text().includes('download') ) {
$('.dynamic').hide();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic">
This text is hidden if another div contains the word "download"
</div>
<div class="something">
<div class="btn-download">
If this text has the word "download" the div with class "dynmaic" is hidden
</div>
</div>
This can help, I'm not an expert but try to edit.
$(document).ready(function() {
$("#dynamic").click(function() {
var res = $('#dynamic').text();
if (res == "value") {
var hide = document.getElementById("something");
hide.style.display = "none";
}
});
});
Your example code needs jQuery. This is a solution using ECMAScript 5 or older and jQuery.
jQuery(document).ready(function($){
if ( $('.btn-download').text().indexOf('download') !== -1) {
$('.dynamic').hide();
}
});
Please check the fiddle https://jsfiddle.net/1sx39q6h/
For jQuery + ECMAScript 6, you have the solution of #jeremy-denis.
This question already has answers here:
Using .text() to retrieve only text not nested in child tags
(30 answers)
Closed 3 years ago.
Is there any way in CSS or jQuery to select only the plain texts inside of an element?
I have an HTML code like this:
<div class="container">
"some text 1"
<div> ... </div>
<img src="#">
"some text 2"
<div> ... </div>
</div>
and want to select only the texts that are directly inside the container element.
I have searched on the internet and found some solutions like using first-child(), nth-child(), last-child() but since the texts are not always in the specific positions; using the *-child() selectors don't solve my problem.
The :nth-child() pseudo-class selector only works with Elements, not with Text Nodes.
In order to do that get the parent node, then get child node collection using childNodes property and finally, you can access TextNode by using index. To remove you can use remove() method or use removeChild() method on parent element.
// get parent elemeent
let cont = document.querySelector('.container');
// get child node collection which is a live collection
let nodeCollection = cont.childNodes;
// get first child
let text1 = nodeCollection[0].textContent;
// get next child(index is 4 since there is an empty text node in between div and img)
let text2 = nodeCollection[4].textContent;
// remove the last element first since nodeCollection is live
// collection removing an element will update the index
nodeCollection[4].remove();
nodeCollection[0].remove();
console.log(text1, text2)
<div class="container">
"some text 1"
<div> ... </div>
<img src="#"> "some text 2"
<div> ... </div>
</div>
<div id="myDiv">
text 1
<div>div text</div>
text 2
<span>span text</span>
</div>
<script>
$(document).ready(function() {
var $myDiv = $('#myDiv');
var texts = [];
for(var i = $myDiv[0].childNodes.length - 1; i >= 0; i--) {// Starting from last to first, so we can remove from array without breaking JS
if($myDiv[0].childNodes[i].nodeType == Node.TEXT_NODE) {// Is text only?
texts.push($myDiv[0].childNodes[i].nodeValue);// Add this text to array
$myDiv[0].removeChild($myDiv[0].childNodes[i]);// Remove from HTML
}
}
texts = texts.reverse();
//texts = ["text 1", "text 2"]
});
</script>
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/
This question already has answers here:
Get only visible text with jquery
(3 answers)
Closed 8 years ago.
I try to get content inside element and i want that is the same when it shown on browser
Example
<pre class="yyy">Hello this is <span style="display: none;"> test </span> text </pre>
and
// how to alert (get) content like when it shown on browser: Hello this is text
alert($(".yyy").html());
I want alert result is: Hello this is text the same when it shown on browser. Is that possible? how to do that thank.
Here is my code
I would do this :
alert($(".yyy").clone().find(':not(:visible)').remove().end().text());
Demonstration
I think this is what you are looking for.
jQuery.fn.visibleText = function() {
return $.map(this.contents(), function(el) {
if (el.nodeType === 3) {
return $(el).text();
}
if ($(el).is(':visible')) {
return $(el).visibleText();
}
}).join('');
};
alert($(".yyy").visibleText());
Here is a fiddle.
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();