Remove all elements that satisfy a condition - javascript

<div class="myClass1">
<span>tesutokana</span>
</div>
<div class="myClass2">
<span>tesutoroma</span>
</div>
<div class="myClass1">
<span>-</span>
</div>
<div class="myClass2">
<span>-</span>
</div>
<div class="myClass1">
<span>-</span>
</div>
<div class="myClass2">
<span>-</span>
</div>
I want to remove all divs that are just <span>-</span> from classes myClass1 and myClass2. Tried with .each() but I can't seem to get the hang of it, mostly with what are the arguments of the function I should call. Any help?

You can do it by comparing the content of the span in a condition:
$('.myClass1, .myClass2').each(function(){
var mySpan = $(this).find('span');
if(mySpan.text() == '-'){
mySpan.closest('div').remove();
}
});
Living example: http://jsfiddle.net/8CNkW/2/
Update:
This one doesn't have the problem with texts containing the - string such as ---, test-test etc.
Plush, is 80% faster than the contains option named in other answers: http://jsperf.com/just-a-demo

Use the :contains selector
$("div span:contains(-)").remove();
Remove the whole div:
$("div span:contains(-)").parent().remove();
JSFiddle
Note that this is a quick and dirty solution as it'll remove all spans that contain a -

You could use .filter() to do the filtering.
Just like that:
$('.myClass1,.myClass2').filter(function(i, el){ return el.innerHTML.trim() == '<span>-</span>' }).remove()

here is a simple solution. fiddle
var doc = document.body;
doc.innerHTML = doc.innerHTML.replace(/<div(\s)+(.)*class="myClass(1|2)"(.)*>(\s|\n|\t)*<span>-<\/span>(\s|\n|\t)*<\/div>/ig,'');
this may be the fastest solution because it's not using a loop or an external library.
or
var j = document.getElementsByClassName('myClass1');
var t = document.getElementsByClassName('myClass2');
var x = t.length--;
while(x--) {
t[x].innerHTML = t[x].innerHTML.replace(/(<span>-<\/span>)/g,'');
}
x = j.length--;
while(x--) {
j[x].innerHTML = j[x].innerHTML.replace(/(<span>-<\/span>)/g,'');
}
fiddle

I would use .filter().
$('div').filter(function(){
var $spans = $(this).find('> span');
return $spans.length === 1 && $spans.text() === '-';
}).remove();
Here's a quick demo: http://jsfiddle.net/VbpzZ/1/

Related

How to target tag after a class?

<div class="pre-class">
<div>100%</div>
</div>
I'm trying to remove the percent (%) on the text inside the div after the class pre-class with textContent.replace("%","") but I just can't target that specific div
(I'm working on a longer website with a lot of divs and I can't add an ID to it because it's from a shortcode.)
I thought I could do something like this:
var textContent = document.getElementsByClassName('gamipress-progress-bar-completed').getElementsByTagName('div');
You're basically there. Don't forget that getElementsByClassname returns an array, so simply use [0] to retrieve the element. You'll see it working in the snippet below:
var textContent = document.getElementsByClassName('pre-class')[0].getElementsByTagName('div')[0].innerHTML;
console.log(textContent)
<div class="pre-class">
<div>100%</div>
</div>
You can use querySelector
let div = document.querySelector('div.pre-class > div');
div.innerText = div.innerText.replace('%', '')
<div class="pre-class">
<div>100%</div>
</div>
If the div will be the first direct child of the pre-class div, and you have one element with "pre-class" class, this will work
const textContent = document.querySelector('.pre-class').firstElementChild.textContent;
console.log(textContent.replace('%', ''))
<div class="pre-class">
<div>100%</div>
</div>
const content = document.querySelector('.pre-class > div').innerHTML;
content.replace("%", "");
<div class="pre-class">
<div>100%</div>
</div>
This is another way of selecting the div nested in your .pre-class div. Perhaps not the best way of doing this but it's handy to know querySelector works.
If you have lots of divs inside div.pre-class , its better to add specific data attribute to each child div and select the desired div using this:
< div class = 'pre-class' >
<div data-order = 'first' > 1 < /div>
<div data-order = 'second' > 2 < /div>
<div data-order = 'third' > 3 < /div>
</div>
///////////
document.querySelector('div[data-order="first"]')
let containers = document.getElementsByClassName("pre-class");
for (var i = 0; i<containers.length; i++) {
let current = containers[i];
let textNode = current.children[0];
textNode.innerText = textNode.innerText.replace(/(\d)%/, '$1');
};
<div class="pre-class">
<div>100%</div>
</div>
Alternatively, you could use element.querySelector() (or querySelectorAll) to find the correct element(s) to replace.
let textNode = document.querySelector(".pre-class > div"); // use querySelectorAll in case there can be multiple matches.
textNode.innerText = textNode.innerText.replace(/(\d)%/, '$1');
<div class="pre-class">
<div>100%</div>
</div>
Use the child selector (>).
let textDiv=document.querySelector(".pre-class > div");
textDiv.textContent=textDiv.textContent.replace("%","");
This will replace the first direct div inside .pre-class. You can adjust the position of divs using pseudo classes. Like for example, if you want to select the second div inside .pre-class, you would use:
<div class="pre-class">
<div>100%</div>
<div>200%</div>
<div>300%</div>
</div>
let textDiv=document.querySelector(".pre-class > div:nth-child(2)");
textDiv.textContent=textDiv.textContent.replace("%","");

A function to remove specified elements

I need to create a function which gets user input (a css selector) and removes all of those elements.
This is the function so far
function removeBySelector(selector) {
var thisOne = document.querySelectorAll(selector);
for(var i = 0; i<thisOne.length; i++) {
document.removeChild(thisOne[0]);
};
};
and the HTML that starts it
<button type="button" name="button" onclick="removeBySelector(prompt('Type the selector e.g p/ p.pClass'));">Remove By Selector</button>
change your method to
function removeBySelector(selector)
{
var thisOne = document.querySelectorAll(selector);
for(var i = 0; i<thisOne.length; i++)
{
thisOne[i].parentNode.removeChild( thisOne[i] ); //changed parentElement to parentNode
};
}
i'd advise using the framework jQuery! It is a very powerful tool that helps you simplify and improve your JavaScript code and it's performance.
With jQuery you can easily use this piece of code to remove any elements by CSS selector.
// Use any CSS Selector here
var elements = $(".class");
$.each(elements, function(){
$(this).remove();
)};
This keeps your code very easy to read and has a high performance.
//Try this code:
var removeElement=function(selector){
$(document).find(selector).remove();
};
removeElement('h1'); // will remove all H1 elements from Document.
You can do the same, without using any library with pure javascript (ES6 syntax in this case):
let elements = document.querySelectorAll(".please-remove");
elements.forEach(e => e.remove());
<div>
<div class="keep">Keep this element</div>
<div class="please-remove">1</div>
<div class="please-remove">2</div>
<div class="please-remove">3</div>
<div class="please-remove">4</div>
<div class="please-remove">5</div>
<div class="please-remove">6</div>
</div>

How to get all CSS classes of an element?

I have an element with multiple classes and I'd like to get its css classes in an array. How would I do this? Something like this:
var classList = $(this).allTheClasses();
No need to use jQuery for it:
var classList = this.className.split(' ')
If you for some reason want to do it from a jQuery object, those two solutions work, too:
var classList = $(this)[0].className.split(' ')
var classList = $(this).prop('className').split(' ')
Of course you could switch to overkill development mode and write a jQuery plugin for it:
$.fn.allTheClasses = function() {
return this[0].className.split(' ');
}
Then $(this).allTheClasses() would give you an array containing the class names.
Note that you can also use myElement.classList as a simple array-like object:
const classList = myElement.classList;
This is supported by all major browsers for a while now, apart IE 9 and below.
This should do the work for you:
var classes = $('div').attr('class').split(" ");
This would be the jQuery solution for other solutions there are other answers !
Check this out:
var classes = $('selector').prop('classList');
element.classList.value
console.log("class")
console.log(document.getElementById('c2').classList.value)
<div id="c2" class="class1 class2"> i am two class</div>
getAttribute
console.log("class")
console.log(document.getElementById('c2').getAttribute('class'))
<div id="c2" class="class1 class2"> i am two class</div>
className
console.log("class")
console.log(document.getElementById('c2').className)
<div id="c2" class="class1 class2"> i am two class</div>
to make an array choose any one of above method
string.split(' ');
function showClasses() {
const div = document.querySelector('div');
const classes = div.className.split(' ');
const p = document.querySelector('p');
p.innerHTML = classes;
}
<div class="foo bar">This div has foo, bar classes</div>
<p class='output'>Above div classes appear here</p>
<button onClick="showClasses();">Show div classes</button>
HTML
<div class="foo bar">This div has foo, bar classes</div>
Vanilla JavaScript. It will return an array of classes.
const div = document.querySelector('div');
const classes = div.className.split(" "); // ['foo', 'bar']

Is there a JS/jQuery Fully Recursive child node count function?

Folks,
Let's say that I have the following situation:
<div class="outer">
<div>
<span>
<ul>
<div> </div>
<div> </div>
</ul>
</span>
</div>
</div>
How would I find the total number of elements inside div.outer? Something like $('div.outer').children().size() or length returns 1 (I'm looking, in this case, for 5) is there a shortcut or function to find the total element count using js/jQuery or should I write a function just for this issue? TIA.
var totalDescendants = $('div.outer *').length;
and done.
var totalDescendants = $('div.outer').find('*').length;
would also work.
A simple (and likely faster than jQuery) JavaScript alternative would be
var el = document.getElementById("foo");
var descendantElementCount = el.getElementsByTagName("*").length;
This does assume you've given the element an id. You could use jQuery to get all the elements with class outer, if this is important:
var descendantElementCount = 0;
$('div.outer').each(function() {
descendantElementCount += this.getElementsByTagName("*").length;
});
jQuery recursive child node count function:
jQuery(document).ready(function(){
var totalChildren=jQuery("*","div.outer").length;
});

How do you use jQuery to find an element by its html?

I am trying to find a way to use jQuery to get the first empty div with a certain class. I tried this:
$(".box[html='']").
but it didn't work. Is there an easy way to do this?
That syntax only works for attributes. For HTML contents, you can use .filter():
$('.box').filter(function () {
return $.trim($(this).html()) === '';
}).eq(0);
Edit: The problem with :empty is that line-breaks and spaces are not empty. So:
<div> </div>
<div>
</div>
... won't match.
This should work:
$('.box:empty:first')
http://api.jquery.com/empty-selector/
How about this:
You html:
<div class="empty"></div>
<div class="empty"></div>
your script:
$(document).ready(function(){
$(".empty:empty:first").html("JJJJ");
});
Check this
http://jsfiddle.net/y4Ef2/
var boxEq;
$('div.box').each(function(i,obj){
if (boxEq === void(0)) {
if ($(obj).html() === '') {
boxEq = i;
break;
}
}
});
// this is your div
$('div.box').eq(boxEq);
Try this one:
$('.box').each(function(){
if($(this).text().length == 0)
//box is empty
});
$("div.box:empty").eq(0)
added .eq(0) since you said first empty

Categories