I am using latest Jquery and the following script:
<script type="text/javascript">
$(document).ready(function(){
var el = $('.title');
el.html(el.html().replace(/\./gi, " "));
});
</script>
This is the div:
<div class="title">The.quick.brown.fox</div>
What it does is replaces all dots with spaces in a DIV with class "title" and really it works fine for this job.
But I have many DIVs with the same "title" class with different strings in them and i need them all to have dots replaced with spaces. But here the problem appears as all what i get is the same result string on all these DIVs "The quick brown fox" while all result strings should be different as all source strings are different...
What do i do to get dots replaced in all DIVs with class "title" and all different strings in each DIV?
Thanks
You can use each() to iterate over the matched elements, or pass a function to html() and compute the new text there:
$(document).ready(function() {
$(".title").html(function(index, currentHtml) {
return currentHtml.replace(/\./gi, " ");
});
});
Just use jQuery each method to iterate over all elements with class .title:
$(document).ready(function(){
$('.title').each(function(){
$(this).html($(this).html().replace(/\./gi, " "));
});
});
As long as you have only text inside your divs, suggested functions will work just fine. However, to allow arbitrary html (like The.quick.brown <img src='fox.jpg'>) the code should be more accurate.
$('.title').each(function() {
if (this.nodeType == 3)
this.nodeValue = this.nodeValue.replace(/\./g, " ");
else
$(this).contents().each(arguments.callee);
});
Basically, you recursively iterate over all descendants of a node and replace only nodes of type 3 (=text).
Fiddle: http://jsfiddle.net/jZgUY/
Related
I got a piece html code like this:
<div><span>span_text</span>div_text</div>
I want to change 'div_text' with jQuery, tried with $.text('changed_div_text') but failed, result like this which is not what I want.
let tmpl = '<div><span>span_text</span>div_text</div>'
let $ = cheerio(tmpl)
console.log($.text()) // span_textdiv_text
$.text('changed_div_text')
console.log($.text()) // changed_div_text
As you can see, text() function will change inner text also, hope someone know a way to solve this problem, thanks!
jQuery doesn't offer a lot of methods that act directly on text nodes. You can use contents to find all child nodes (including text nodes), and you can use filter to find only text nodes, and then you can modify their nodeValue to change their text. Example:
// Get just the text nodes
var textNodes = $("#target").contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
});
// In this case, I just replace the text with "Index n" where n is the index
textNodes.each(function(index) {
this.nodeValue = "Index " + index;
});
<div id="target"><span>span_text</span>div_text</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you have to know the text div_text is the childNode of div,and it is kind of textNode
var div=document.createElement('div');
div.innerHTML='<div><span>span_text</span>div_text</div>';
div.childNodes[0].childNodes[1].textContent='test';
console.log(div.innerHTML);//<div><span>span_text</span>test</div>
if you want to change the text,you can change the value of the textNode,for example,change the textContent ,innerText or innerHTML,,,
your html code is <div><span>span_text</span>div_text</div>
for your understanding I am assuming a button with id btn. clicking this button the text will be changed
button code <button id="btn">change</button>
now if you want to change all the child text of the div then the below code will work fine.
$(document).ready(function(){
$("#btn").click(function(){
$("div > span").text("changed_div_text");
});
});
now if you only want to change the last child of the div then the code is below
$(document).ready(function(){
$("#btn").click(function(){
$("div > span:last-child").text("changed_div_text");
});
});
hope it will solve your issue
<p>some string here xxx</p>
I want to remove the xxx characters
so I do $(p:contains('xxx')).remove(); but it removed the entire <p></p>, how to only get rid of the targeted character?
That would be the text method and a string replace
$('p').text(function(_, txt) {
return txt.replace('xxx', '');
});
remove removes entire elements, not parts of text.
That is the expected behavior of remove(), it removes whole elements . You can use text(fn) or html(fn) to do it.
$("p:contains('xxx')").text(function(idx, oldText){
return oldText.replace('xxx','');
});
If you also have other tags within the p use html(fn) as above
I only want to display the first four characters of a div, but it seems to be more difficult than needed and google isn't very helpful. Different variations of this don't seem to work:
$("#div").html(this.html().substring(0,4));
I really want to avoid having an extra variable in there that stores the text first.
Use a callback for the .html(),
$('#div').html(function(i, currentHtml) {
return currentHtml.substring(0, 4);
});
Demo
You can also use .text() in this case if the div consists only of plain text.
$("#div").text(function(i, currentText) {
return currentText.substring(0, 4);
});
Refer :
Slice vs Substring
Turns out substring is relatively faster.
JsPerf test : slice() vs substring() vs others
If the div elements contains any HTML (html elements) then .html() return the it's as a string. Example
Note: (It's completely depend on the inner content of you div)
If you want to truncate the plain text, you should use .text() instead of using .html()
Try this:
$("#div").text(function(){
return $(this).text().substring(0,4);
});
Working Fiddle
Try this :
$("#div").html(function(){
return $(this).html().substring(0,4)
});
It will count space also...If any there.
Like DIV have "test four 3" will give you output "test"
Use slice() for this purpose :
$("#div").text(function(){
return $(this).text().slice(0,4);
});
I have the following HTML :
<div id="rightCon">
</div>
And then I have the following script at the top :
$('#rightCon:empty').hide();
Why is the div not hiding? I can see that there is some spaces(that I can´t get ridoff) but does that really matter? How do I remove/hide this div when its empty with only spaces?
Your element appears to have a bunch of white space, which will give it a text node. It won't be matched by :empty for that reason.
You could try finding the element and checking it's contents explicitly:
$('#rightCon').filter(function() {
var text = $(this).text().replace(/\s*/g, '');
return !text;
}).hide();
This solved the problem.
$(document).ready(function () {
if($('#rightCon').text().trim().length < 1)
{$('#rightCon').hide();}
});
Your div is not actually empty (It contains whitespace). So the selector $("#rightCon:empty") will never evaluate and hide the div.
Since HTML elements should be unique, you can safely assume that you can select the correct element via:
var rightCon = $("#rightCon");
You can then hide the element via:
right.hide();
Or
$("#rightCon").hide();
Why the following code not work as expected? (Select all elements before the div with class = clear?)
HTML:
<div id="text">
line0
<div>line1</div>
<div>line2</div>
<div class="clear" />
<div>dummy</div>
<p>dummy</p>
</div>
JS:
var allow = true;
var output = $('#text *').filter(function(index) {
if( $(this).attr("class") == 'clear') {
allow = false;
}
return allow;
}).html().trim();
alert( output );
Output:
line1
Expect:
line0
line1
line2
This happens because as the .html() says
Get the HTML contents of the first element in the set of matched
elements.
So though both of your div is selected only one is returned by .html()
Check this fiddle to verify you code is returning both elements.
And as other have already said you should use the .hasClass method.
UPDATE
As that line0 is not inside any node, its a textNode, You can loop and add span tags around textNodes first. Or you wont be able to apply styling to that text. Check the following code
var whitespace = /^\s*$/;
$('#text').contents().filter(function(){
return this.nodeType == 3 && !whitespace.test(this.nodeValue);
}).wrap('<span></span>');
This loops through all childNodes(including textnodes) and wrap non-space textnodes with span.
So after that your line0 will be inside a span tag like <span>line0</span>. So now if you do
$('.clear').prevAll().css('color', 'red');
It will highlight line0 too.
Check Node Types Doc on MDN
Working Fiddle
Because the html() method returns the contents of the first element in the selector.
http://api.jquery.com/html/
If the selector expression matches more than one element, only the first match will have its HTML content returned.
$('.clear').prevAll().css('color', 'red').fadeOut(2000);
Live DEMO
And by the way, if you want to check if an element has a class use .hasClass(class)
Example:
var hasClass = $(this).hasClass('clear');