jQuery Remove elements where the content is empty - javascript

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();

Related

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);
}
}

detecting a span while looping using jquery/js?

I wanted to detect a span element while looping through a div element i.e.
<div class="example">
These are some <span id ="special" class="anime">special</span> words
that should be faded in one after the other.
</div>
using javascript i split the words and fade them in one by one i.e.
JS:
function doSomething(spanID) {
alert(spanID);
}
var $el = $(".example:first"), text = $.trim($el.text()),
words = text.split(" "), html = "";
for (var i = 0; i < words.length; i++) {
html += "<span>" + words[i] + ((i+1) === words.length ? "" : " ") + "</span>";
};
$el.html(html).children().hide().each(function(i){
// if special span is detected
// get the span id pass it to doSomething function
$(this).delay(i*200).fadeIn(700);
});
$el.find("span").promise().done(function(){
$el.text(function(i, text){
return $.trim(text);
});
});
working example is here: http://jsfiddle.net/6czap/5/
everything works, it just that i need to detect any special spans so i can do something with them, and then the for loop should carry on doing what it deos. thanks
Try the following:
var orig = $(".example:first").html()
$el.html(html).children().hide().each(function(i){
$(this).delay(i*200).fadeIn(700);
}).promise().done(function(){
$('.example:first').html(orig);
});
demo!

Access Elements inside the span element

I have a block of code like this
<span class='Wrapper'>
<span class="title"></span>
<span class="body">
<ul class="items">
<li></li>
<li></li>
</ul>
<span>
</span>
Once I access the span wrapper element using document.getElementsByTagName('span');
how do I access the inner span elements with title class and the ul elements of the span element with class body.I need to do this using plain javascript
First get an array holding all the span elements:
var yourSpans = document.getElementsByTagName('span');
Then then loop over each element in the array checking if the element has the specific class:
for(var i in yourSpans){
if (yourSpans[i].className == "title" || yourSpans[i].className == "body") {
// your code here
}
}
var spans = document.getElementsByTagName('span');
would return an array of spans. You would access the spans using spans[0], spans[1], etc.
Adding to reagan's answer, you would then need to do something like
for( var i = 0, j= spans.length; i < j; i+=1 ) {
var classes = span[i].getAttribute("class");
if( classes ) {
if( classes.indexOf("your_class_name") != -1) {
//span[i] is one of thelements you need containing 'your_class_name'.
}
}
}
I would really recommend using jQuery, it would make your life a lot easier!
$('.title').dostuff...
But if you want a JS only solution, here you go...
function editClass(matchClass,content) {
var elems = document.getElementsByTagName('*'),i;
for (i in elems) {
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1) {
elems[i].innerHTML = content;
}
}
}
Here is a fiddle (Pure-JS, no jQuery) as an example.

Wrap text with <span> element using Javascript or jQuery

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);

Remove all tags except for img tag

I need an regular expression or something else to remove all tags in a contentEditable div, but to keep img tag with specific class or id, how I can do this?
Now I use:
.replace(/(<\/?.*?>)/gi, '');
but it removes all tags.
I made this :
var element = document.getElementById("myDiv").children;
for(var i=0; i<element .length;i++)
{
if(element[i].tagName != "IMG" || element[i].className != "requiredClassName")
{
element[i].parentNode.removeChild(element[i]);
}
}
var child=document.getElementById('editableDIV').firstChild;
while(child) {
var removeNode=null;
if(child.tagName&&(child.tagName.toUpperCase()!=='IMG'||
child.id!=='myid'||
child.className!=='myclass')) removeNode=child;
child=child.nextSibling;
if(removeNode)removeNode.parentNode.removeChild(removeNode);
}
( if you need plain JS ): Maybe the better way is to collect all elements then after check their class/id and perform action. Good idea is to use DOM, not regexp. DOM is for HTML elements manipulation.
( or use jQuery ): Simple code can do that thing. Just collect all div's children and check their class in .each() loop;
For e.g.:
$('#contentEditable').each( function( index ) {
if( !this.is( 'img' ) && ( this.is('.someclass') || this.is('#someid') ) ) {
this.remove();
}
});
Hope it helps you.
P.S.:
Be careful when you are using greedy quantification .*
It will get all text between any < >, so if you have code listed below regexp (<\/?.*?>) will collect whole code.
<div class="container">
<div id="header">
<div id="portalLink">
<a class="genu" href="http://stackexchange.com">Stack Exchange</a>
</div>
</div>
</div>
var editableDiv = document.getElementById("MyEditableDiv")
var editableDivImgs = editableDiv.getElementsByTagName("img")
for (var i = 0; i < editableDivImgs.length; i++) {
if(editableDivImgs[i].className != "safe")
{
editableDivImgs[i].parentNode.removeChild(editableDivImgs[i])
}
}
have you tried something like that?
Instead of removing all other elements extract all imgs and concatenate them into a new string:
var regex = /<img.*?>/gmi;
var imgsOnly = '';
var img;
while( ( img = regex.exec(str) ) !== null ) {
imgsOnly += img;
}
alert( imgsOnly );

Categories

Resources