Wrap text with <span> element using Javascript or jQuery - javascript

I have the following HTML code on my page. There is no containing element, it's just in the body.
<b>SqFt per Carton: </b>24.30<br>
Using script, I want to wrap 24.30 in a span tag with a class so the result will look like this:
<b>SqFt per Carton: </b><span class="sqft_cart">24.30</span><br>
How can I do this?

Here is jQuery way to achieve what you asked for by iterating over all text nodes (i.e. text without any tag) in the document, and in case they come right after <b> tag replace them with <span> having proper class:
$(document).ready(function() {
$("body").contents().filter(textNodeFilter).each(function(index) {
var textNode = $(this);
if (this.previousSibling && this.previousSibling.tagName.toLowerCase() === "b") {
var value = textNode.text();
var oSpan = $("<span>").html(value).addClass("sqft_cart");
textNode.replaceWith(oSpan);
}
});
});
function textNodeFilter() {
return this.nodeType == 3;
}
Live test case.

$("b").parent().contents().filter(function() {
return this.nodeType != 1;
}).wrap("<span class='sqft_cart'></span>");
http://jsfiddle.net/FW8Ct/4/

Since you don't have a containing element you can use .nextSibling() to get the text node for 24.30. Then .insertAdjacentHTML() inserts the new span after deleting the old text node. Since I don't know what the rest of your page looks like, I'll assume there could be multiple <b> elements, but the code will work either way.
Demo: http://jsfiddle.net/ThinkingStiff/6ArzV/
Script:
var bs = document.getElementsByTagName( 'b' );
for( var index = 0; index < bs.length; index++ ) {
if( bs[index].innerHTML.indexOf( 'SqFt per Carton:' ) > -1 ) {
var text = bs[index].nextSibling,
span = '<span class="sqft_cart">' + text.nodeValue + '</span>';
text.parentNode.removeChild( text );
bs[index].insertAdjacentHTML('afterEnd', span);
};
};
HTML:
<b>SqFt per Carton: </b>24.30<br>
<b>Price per Carton: </b>193.00<br>
<b>SqFt per Carton: </b>12.90<br>
<b>Price per Carton: </b>147.00<br>
<b>SqFt per Carton: </b>14<br>
CSS:
.sqft_cart {
color: red;
}
Output:

you could get the value of SqFt per Carton: 24.30 by using
var takentext = $("class Or ID of SqFt per Carton").text();
$("class of span").text(takentext);

Related

jQuery Remove elements where the content is empty

I want to remove the elements where there is no content. For example this is my HTML markup:
I have the html markup in a jquery variable say var myhtml and I am not sure of any specific tags in it.
<h1>
<u>
<strong></strong>
</u>
<u>
<strong>Read This Report Now
<strong></strong> ??
</strong>
</u>
</h1>
As we can see that above markup
<u>
<strong></strong>
</u>
is empty and hence this should be removed from the markup. Say I have the above markup in a variable myhtml. How can I do this?
I am not sure if the element will be either
"<u>" or "<em>" or "<i>" or "<div>" or "<span>"
.. It can be anything.
You can search all elements and remove which is empty.
$('*').each(function(){ // For each element
if( $(this).text().trim() === '' )
$(this).remove(); // if it is empty, it removes it
});
See how works!: http://jsfiddle.net/qtvjj3oL/
UPDATED:
You also can do it without jQuery:
var elements = document.getElementsByTagName("*");
for (var i = 0; i < elements.length; i++) {
if( elements[i].textContent.trim() === '' )
elements[i].parentNode.removeChild(elements[i]);
}
See jsfiddle: http://jsfiddle.net/qtvjj3oL/1/
UPDATED 2:
According to your comment, you have the html in a variable, you can do it:
// the html variable is the string wich contains the html
// We make a fake html
var newHtml = document.createElement('html');
var frag = document.createDocumentFragment();
newHtml.innerHTML = html;
frag.appendChild(newHtml);
var elements = newHtml.getElementsByTagName("*");
// Remove the emptys elements
for (var i = 0; i < elements.length; i++) {
if( elements[i].textContent.trim() === '' )
elements[i].parentNode.removeChild(elements[i]);
}
html = newHtml.innerHTML; // now reset html variable
It works: http://jsfiddle.net/qtvjj3oL/6/
try
$("u").each(function () { // if remove all, you can select all element $("*")
var x = $(this).text().trim();
if (x == "") {
$(this).remove();
}
});
IF you want remove everything simply you can use empty selector then remove it
DEMO
JQuery
It searches all elements and remove all blank elements (ie: <span></span>), all elements which contains a simple space (ie: <span> </span>) and all elements which contains only a (ie: <span> </span>)
$(".mydiv *").each(function() {
var $this = $(this);
if($this.html().replace(/\s| /g, '').length == 0)
$this.remove();
});
DEMO: http://jsfiddle.net/7L4WZ/389/
simply:
$( ":empty" ).remove();
or
$( "u:empty" ).remove();
if specific
You can use .filter() and remove() for this
$('*').filter(function() {
return $(this).text().trim() == ""
}).remove();
If your html is already in a variable myhtml here is how you would do it:
$('*', myhtml).filter(function() {
return $(this).text() == '';
}).remove();

Determining a character of a sentence when clicked on

On a random break I found myself wondering if it would be possible to use jQuery to determine a single character within a sentence when it is clicked on.
For example:
This
When the user clicks on first h, jQuery would return this to me.
The only way I could think of doing this would be to wrap each character within the sentence in a span with a class of its letter such as the following example:
<span class="clickable T">T</span>
<span class="clickable h">h</span>
<span class="clickable i">i</span>
<span class="clickable s">s</span>
Followed by a $('.clickable').click(function()) that would return its second class.
My question is: is this the most efficient way to do this?
Obviously wrapping every single letter of the document in span tags is not efficient.
I was able to spin something up that works in Chrome at least. Basically, when you click on a letter, it then triggers a double clicks which selects the word. We get the selection which actually gives us the text of the entire target element. From that, we get the letter that was clicked. We remove the selection and do what we want with the letter.
Fiddle here
$(function(){
$(document).click(function(e){
var target = e.target;
$(target).dblclick();
}).dblclick(function(){
var selection,
node,
text,
start,
end,
letter;
if (window.getSelection) {
selection = document.getSelection();
node = selection.anchorNode;
if (node.nodeType === 3) {
text = node.data;
start = selection.baseOffset;
end = selection.extentOffet;
if (!isNaN(start)) {
letter = text.substr(start, 1);
}
}
window.getSelection().removeAllRanges()
} else if(document.selection) {
//continue work here
}
if (letter) {
alert(letter);
}
});
});
You could return the innerHTML as well with:
$('.clickable').on('click', function(){
alert($(this).html());
});
As for a more efficient way to do it...maybe try this:
in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?
You can do it with this script
$('.clickable').on('click', function(){
var html = $(this).text(); // if you want the text inside the span
var index = $(this).index(); // if you want the position among siblings
var classes = $(this).attr('class').split(" ");
var secondClass = getSecondClass(classes);
});
function getSecondClass(classArray){
if(classArray.length<2){
return null;
}else{
return classArray[1];
}
}
I've also included the html and index variables if you want to do something else with the clicked element.
Basically you split the classes of the element by spaces and then check if the array has less than two elements, in that case it returns null, otherwise it returns the second element.
jsFiddle
Well wrapping all text dyanamically with span tag , it is possible what you were looking for
JS
$(function(){
var lengthText = $('#singlecharacter').text().length;
var textValue = $('#singlecharacter').text();
var textArray = textValue.split('');
var newText = new Array();
for (var i = lengthText - 1; i >= 0; i--) {
newText[i] = "<span class='sp'>"+textArray[i]+"</span>";
};
$('#singlecharacter').html(newText);
$('.sp').click(function()
{
alert($(this).text());
});
});
HTML
<div id='singlecharacter'>THIS</div>
DEMO JSFIDDLE

Jquery remove the innertext but preserve the html

I have something like this.
<div id="firstDiv">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</div>
I want to remove 'This is some text' and need the html elements intact.
I tried using something like
$("#firstDiv")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text("");
But it didn't work.
Is there a way to get (and possibly remove, via something like .text("")) just the free text within a tag, and not the text within its child tags?
Thanks very much.
Filter out text nodes and remove them:
$('#firstDiv').contents().filter(function() {
return this.nodeType===3;
}).remove();
FIDDLE
To also filter on the text itself, you can do:
$('#firstDiv').contents().filter(function() {
return this.nodeType === 3 && this.nodeValue.trim() === 'This is some text';
}).remove();
and to get the text :
var txt = [];
$('#firstDiv').contents().filter(function() {
if ( this.nodeType === 3 ) txt.push(this.nodeValue);
return this.nodeType === 3;
}).remove();
Check out this fiddle
Suppose you have this html
<parent>
<child>i want to keep the child</child>
Some text I want to remove
<child>i want to keep the child</child>
<child>i want to keep the child</child>
</parent>
Then you can remove the parent's inner text like this:
var child = $('parent').children('child');
$('parent').html(child);
Check this fiddle for a solution to your html
var child = $('#firstDiv').children('span');
$('#firstDiv').html(child);
PS: Be aware that any event handlers bounded on that div will be lost as you delete and then recreate the elements
Why try to force jQuery to do it when it's simpler with vanilla JS:
var div = document.getElementById('firstDiv'),
i,
el;
for (i = 0; i< div.childNodes.length; i++) {
el = div.childNodes[i];
if (el.nodeType === 3) {
div.removeChild(el);
}
}
Fiddle here: http://jsfiddle.net/YPKGQ/
Check this out, not sure if it does what you want exactly... Note: i only tested it in chrome
http://jsfiddle.net/LgyJ8/
cleartext($('#firstDiv'));
function cleartext(node) {
var children = $(node).children();
if(children.length > 0) {
var newhtml = "";
children.each(function() {
cleartext($(this));
newhtml += $('<div/>').append(this).html();
});
$(node).html(newhtml);
}
}

How to select a part of string?

How to select a part of string?
My code (or example):
<div>some text</div>
$(function(){
$('div').each(function(){
$(this).text($(this).html().replace(/text/, '<span style="color: none">$1<\/span>'));
});
});
I tried this method, but in this case is selected all context too:
$(function(){
$('div:contains("text")').css('color','red');
});
I try to get like this:
<div><span style="color: red">text</span></div>
$('div').each(function () {
$(this).html(function (i, v) {
return v.replace(/foo/g, '<span style="color: red">$&<\/span>');
});
});
What are you actually trying to do? What you're doing at the moment is taking the HTML of each matching DIV, wrapping a span around the word "text" if it appears (literally the word "text") and then setting that as the text of the element (and so you'll see the HTML markup on the page).
If you really want to do something with the actual word "text", you probably meant to use html rather than text in your first function call:
$('div').each(function(){
$(this).html($(this).html().replace(/text/, '<span style="color: none">$1<\/span>'));
// ^-- here
}
But if you're trying to wrap a span around the text of the div, you can use wrap to do that:
$('div').wrap('<span style="color: none"/>');
Like this: http://jsbin.com/ucopo3 (in that example, I've used "color: blue" rather than "color: none", but you get the idea).
$(function(){
$('div:contains("text")').each(function() {
$(this).html($(this).html().replace(/(text)/g, '<span style="color:red;">\$1</span>'));
});
});
I've updated your fiddle: http://jsfiddle.net/nMzTw/15/
The general practice of interacting with the DOM as strings of HTML using innerHTML has many serious drawbacks:
Event handlers are removed or replaced
Opens the possibility of script inject attacks
Doesn't work in XHTML
It also encourages lazy thinking. In this particular instance, you're matching against the string "text" within the HTML with the assumption that any occurrence of the string must be within a text node. This is patently not a valid assumption: the string could appear in a title or alt attribute, for example.
Use DOM methods instead. This will get round all the problems. The following will use only DOM methods to surround every match for regex in every text node that is a descendant of a <div> element:
$(function() {
var regex = /text/;
function getTextNodes(node) {
if (node.nodeType == 3) {
return [node];
} else {
var textNodes = [];
for (var n = node.firstChild; n; n = n.nextSibling) {
textNodes = textNodes.concat(getTextNodes(n));
}
return textNodes;
}
}
$('div').each(function() {
$.each(getTextNodes(this), function() {
var textNode = this, parent = this.parentNode;
var result, span, matchedTextNode, matchLength;
while ( textNode && (result = regex.exec(textNode.data)) ) {
matchedTextNode = textNode.splitText(result.index);
matchLength = result[0].length;
textNode = (matchedTextNode.length > matchLength) ?
matchedTextNode.splitText(matchLength) : null;
span = document.createElement("span");
span.style.color = "red";
span.appendChild(matchedTextNode);
parent.insertBefore(span, textNode);
}
});
});
});

Jquery Hide Class when no class is present

I have some text below called (16 Courses). I need to hide only this text, but I can't seem to hide it no matter what I try using jquery. Is there any help someone could provide so I can hide on this text?
<div id="programAttributes">
<div class="left" id="credits">
<h3>Credits</h3>
<h3 class="cost">48</h3>
(16 Courses)
</div>
<div class="gutter12 left"> </div>
<div class="left" id="costPer">
<h3>Cost Per Credit</h3>
<h3 class="cost">$300</h3>
</div>
</div>
I thought if I could write something like this that would do the trick, but I am so far unsuccessful.
$("#credits:not([class!=h3])").hide();
Usage
// hides in the whole document
hideText("(16 Courses)");
// only hide inside a specific element
hideText("(16 Courses)", $('#programAttributes'));
// make it visible again
showText("(16 Courses)");
[See it in action]
CSS
.hiddenText { display:none; }
Javascript
// escape by Colin Snover
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function hideText(term, base) {
base = base || document.body;
var re = new RegExp("(" + RegExp.escape(term) + ")", "gi");
var replacement = "<span class='hiddenText'>" + term + "</span>";
$("*", base).contents().each( function(i, el) {
if (el.nodeType === 3) {
var data = el.data || el.textContent || el.innerText;
if (data = data.replace(re, replacement)) {
var wrapper = $("<span>").html(data);
$(el).before(wrapper.contents()).remove();
}
}
});
}
function showText(term, base) {
var text = document.createTextNode(term);
$('span.hiddenText', base).each(function () {
this.parentNode.replaceChild(text.cloneNode(false), this);
});
}
You can check for and remove textnodes like this:
​$("#credits").contents().filter(function() {
if(this.nodeType == 3)
this.parentNode.removeChild(this);
});​​​​​​
You can test it here, this gets all the nodes (including text nodes) with .contents(), then we loop through, if it's a text node (.nodeType == 3) then we remove it.
Could you wrap it in a separate span, and then do:
$('#credits span').hide();
?
Try wrapping the text in a span as follows:
<div class="left" id="credits">
<h3>Credits</h3>
<h3 class="cost">48</h3>
<span id="toHide">(16 Courses)</span>
</div>
then you can use jquery:
$("#credits > span)").hide();
the hide() function has to be applied to a DOM element.
I would use a label tag around the text so I can handle it with jquery.
It's textnode. Loop thru all parents nodes and if it's type is textnode, hide it. See also this:
How do I select text nodes with jQuery?

Categories

Resources