Add Html to Text without children element - javascript

I am very confused on how to get this work, did a lot of research online to help find a solution to this, but got nothing. Found this link here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/ but still didnt help much
This is what I am trying to accomplish, the system is outputting text like this, I have no control over the html.
<div class="myclass">
Text 1
Text 2
Text 3
</div>`
but would like to use jquery to insert html around those text
For example:
<div class="myclass">
<span>Text 1 </span>
<span> Text 2 </span>
<span> Text 3</span>
</div>
any help is appreciated
thank you very much

$('.myclass').html(function(i, v){
return '<span>' + $.trim(v).split('\n').join('</span><span>') + '</span>';
});
http://jsfiddle.net/vDp6A/

There are other ways. This would satisfy the question.
$(function(){
stuff=$('.myclass').text().split("\n");
newhtml='';
$.each(stuff, function(i,o){
if (o!=''){
newhtml +='<span>' + o + '</span>'."\n";
}
});
$('.myclass').html(newhtml);
});

This should sort it:
var theDivs = document.getElementsByClassName('myclass');
for(var i in theDivs)
{
if(parseInt(i)==i)
{
var div = theDivs[i];
var text = div.innerHTML.split("\n");
for(var k in text)
{
var trimmed = text[k].replace(/^\s+|\s+$/,'');
if(trimmed != '') text[k] = '<span>'+trimmed+'</span>';
else text[k] = trimmed;
}
div.innerHTML = text.join("\n");
}
}

Related

How can I add element after match character in jquery?

Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example:
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
<script>
var chars = 55;
if ($('#mytext').text().length > chars){
//add <br> after first dot found after number of chars specified.
}
</script>
... The output would be:
This is just a example. I need to find a solution. I will appreciate any help.<br>
Thank you.
You can try this
var chars = 55;
if ($('#mytext').text().length > chars){
var text = $('#mytext').text(); // div text
var chars_text = text.substring(0, chars); // chars text
var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>'); // rest of text and replace dot of rest text with span
$('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again
}
span{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
Note: if you just need to replace the next one dot after chars you can
use '.' instead of /\./g
this way : With JQUERY Substring
<p>
this is test string with jquery . test 1 2 3 4 45 5 . test test test
</p>
<b></b>
<script>
var a = $('p').text();
var _output = '';
var _allow_index = 40;
if (a.length > _allow_index)
{
var x = a.split('.');
for(var i=0; i<x.length; i++)
{ if (_output.length < _allow_index) { _output+=x[i]+'.'; } }
}
else { _output = a; }
$('b').html(_output + '<br>'+a.substr(_output.length,a.length));
</script>
Doing that doesn't seem to be a very good practise, for instance length may vary for localised languages.
Besides, you're assuming you have a plain text, rather than an HTML text and length is different in both cases. You may want to use html() instead of text().
However here is a way for the given case:
var container = $('#mytext');
var length = 55;
var insert = '<br/>';
var text = container.text().trim(); // text() or html()
var dotPosAfterLength = text.indexOf(".", length);
if (dotPosAfterLength != -1) {
container.html(
text.substring(0, dotPosAfterLength+1)
+insert
+text.substring(dotPosAfterLength+1)
);
}
You just need to add this property in CSS.
<div id="mytext">
This is just a example. I need to find a solution.
I will appreciate any help. Thank you.
</div>
<style>
div#mytext{
word-wrap: break-word;
}
</style>

Find out div with class name and remove before and after it

I have a formatted text field which contains..
"this is some text node
<div class="myClass">contents....</div>
some more text node
<div class="myClass">contents....</div>
"
..like this.
Now i want to remove all the surrounding "&nbsp" to those divs which has class="myClass" only i.e the "&nbsp" before and after those divs.
I have gone through this link but it is not solving my problem
jquery how to find if div with specific id exists
Thanks in advance.
I might go for something like
var text = '"this is some text node <div class="myClass"> contents....</div> some more text node <div class="myClass"> contents.... </div> "';
var $ct = $('<div />', {
html: text
});
$ct.find('.myClass').each(function () {
if (this.nextSibling && this.nextSibling.nodeType == 3) {
this.nextSibling.data = this.nextSibling.data.replace(/^\s+/, '');
}
if (this.previousSibling && this.previousSibling.nodeType == 3) {
this.previousSibling.data = this.previousSibling.data.replace(/\s+$/, '');
}
})
var html = $ct.html();
Demo: Fiddle
you can replace '' instead of '& nbsp;',
$('.myClass').html($('.myClass').html().replace(' ',''));
or try like this,
$('.myClass').html(function(i,h){
return h.replace(/ /g,'');});
var text = '"this is some text node <div class="myClass"> contents....</div> "';
var $ct;
$ct = $('<pre />', {
html: text
});
$ct.find('.myClass').each(function () {
if (this.nextSibling && this.nextSibling.nodeType == 3) {
var r = this.nextSibling.data;
this.nextSibling.data = this.nextSibling.data.replace(String.fromCharCode(160), '');
var s = this.nextSibling.data;
this.nextSibling.data = this.nextSibling.data.replace(/^ /, '');
}
if (this.previousSibling && this.previousSibling.nodeType == 3) {
this.previousSibling.data = this.previousSibling.data.replace(String.fromCharCode(160), '');
this.previousSibling.data = this.previousSibling.data.replace(/ /, '');
}
})
var html = $ct.html();
alert(html);
Thanks to all. I just modified Mr. Arun P johny's code a little. And thats worked for me perfectly. In his code it was deleting blank space also, but i wanted to delete &nbsp only.

Wrap HTML around text

This is not ideal, but I am running out of options on trying to wrap some HTML around a heading that I have. It is possible at all to target a header text and wrap HTML around that text?
Starting text:
<div class="header-intro-text">
<h1>New Business Conference</h1>
</div>
Ending Text with added HTML
<div class="header-intro-text">
<h1>New Business Conference</h1>
</div>
Try:
$(".header-intro-text h1").wrapInner('');
You should be able to do the following with jQuery:
$('h1').html('' + $('h1').text() + '');
or for multiple headers
$('h1').each(function() {
$(this).html('' + $(this).text() + '');
});
var hit = $('.header-intro-text h1');
var hitText = hit.text();
hit.html($('').text(hitText));
Demo: http://jsfiddle.net/qwertynl/reV9V/
var word = 'Conference';
function highlight(word){
var $container = $('.header-intro-text');
$container.html(
$container.html().replace(word, ''+word+'')
);
}

JQuery find child element inner text and replace with IMG HTML

I need a little help with a Javascript function I am creating. In essence, I need to loop through a set of DIVs with class .DetailRow and find a child DIV's content (inner text). If this text is matched to a variable, then I need to replace this inner text with an IMG HTML statement.
BTW I am kinda new at this (4 months old!) so apologies if the issue is simple, but I have tried a few combos and I am stuck.
Here's the HTML:
<div class="DetailRow" style="display: ">..</div>
<div class="DetailRow" style="display: ">..</div>
<div class="DetailRow" style="display: ">
<div class="Label">Availability:</div>
<div class="Value">in stock + Free Shipping</div>
</div>
Example, if I find "in stock" in the LABEL inner text, I want to replace it with the value of the variable "instock" which is an IMG HTML statement. See my code attempt below.
<script type="text/javascript">
$(window).load(function(){
var instock = '<img src="https://linktoimgfolder/instock.gif" title="Product available, usually ships 24hrs to 48hrs after order receipt" style="margin-top:-3px;">';
var lowstock = '<img src="https://linktoimgfolder/lowstock.gif" title="Product stcok low, order today so you do not miss out">';
var nostock = '<img src="https://linktoimgfolder/outstock.gif" title="Product out of stock, could ship 1 to 2 weeks after order receipt">';
$('div.DetailRow')each(function(){
if (indexOf($(this).childNodes[1].innerHTML, "in stock") > 0) {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = instock;
} else if (indexOf($(this).childNodes[1].innerHTML, "low stock") > 0) {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = lowstock;
} else {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = nostock;
};
});
});
</script>​
By the way,m I cannot match text exactly as the text beyond the "+" will change from time to time, thus I am trying indexOf.
Many thanks in advance for your assistance!
M
Using the :contains selector
var stock = {'in stock': instock, 'low stock': lowstock, 'no stock': nostock};
Object.keys(stock).forEach(function(key) {
$('div.DetailRow div:contains(' + key + ')').html(stock[key]);
});
jsFiddle Demo
A pure jQuery solution:
$.each(stock, function(key, value) {
$('div.DetailRow div:contains(' + key + ')').html(value);
});
You have typo in this line $('div.DetailRow')each(function(){ and then you can use jQuery .text() and .html() to check value and update.
Try:
$('div.DetailRow').find("div").each(function(){
if($(this).text().indexOf("in stock")!=-1){
$(this).text("");
$(this).html(instock);
}else if($(this).text().indexOf("low stock")!=-1){
$(this).text("");
$(this).html(lowstock);
}else{
$(this).text("");
$(this).html(nostock);
}
});
DEMO FIDDLE
NOTE: Updated code to find div inside div.DetailsRow. Change it according to your requirement.

add what contains in element along with array

I'm trying to add the content of each span along with the value in the title attribute.
<div id="group-wrap" class="group">
<span class="lbracket" title="&f">(</span>
<span class="grouptitle" title="&f"> Group </span>
<span class="rbracket" title="&f">) </span>
<span class="username" title="&f"> Username </span>
<span class="col" title="&f">:</span>
<span class="text" title="&f"> Helo There! </span>
</div>
Here is what I have so far:
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title'));
});
alert(str.join(''));
});
http://jsfiddle.net/B9QeK/3/
The output is &f&f&f&f&f (the value of each title attribute), but the expected output has the value, plus the content that is in the span. The value of the attribute should be appended before the content.
&f(&fGroup&f)&fUsername: &f text
How can I get this result?
Looks like you are looking for
str.push( this.getAttribute('title'), this.textContent || this.text );
As for performance reasons, you should not re-create a jQuery object for every single iteration. Even better, don't use jQuery at all to receive those values.
JSFiddle
And by the way, you can make usage of jQuerys .map() to do it a bit more elegant:
jQuery(function($){
var str = $('#group-wrap span').map(function(){
return this.getAttribute('title') + this.textContent || this.text;
}).get();
alert(str.join(''));
});
JSFiddle
Reference: .map()
jQuery(function($){
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Working JSFiddle
text:
Description: Get the combined text contents of each element in the set of matched elements, including their descendants.
docs
Just use the text method to get the text content of each span:
var str = [];
$('#group-wrap span').each(function(){
//Push value of title attribute and text content into array:
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Your line
str.push($(this).attr('title'));
Should look like:
str.push($(this).attr('title') + $(this).text());
Although, this is making two identical calls $(this), so you might consider caching:
var $this = $(this)
str.push($this.attr('title') + $this.text());
var str = "";
$('#group-wrap span').each(function(){
str+=$(this).attr('title')+$(this).text();
});
alert(str);
});

Categories