How to remove div elements with Javascript? - javascript

Lets say I have a webpage, and all I'm interested is the div with id "content", i.e:
<div id="content"></div>
How do I remove all the other div elements, and just display the div I want?

var all_div_nodes = document.querySelectorAll('div'),
len = all_div_nodes.length,
current = null;
while( len-- ) {
current = all_div_nodes[len];
if( current.parentNode ) {
if( current .id !== 'content' )
current .parentNode.removeChild( current );
}
}
If you can afford using a library like jQuery, this would be even more trivial:
$('div').not('#content').remove();

If you want to remove the sibling DIVs, using jQuery, you can write:
$("#content").siblings("div").remove();

Related

Select element by tag/classname length

I'd like to select an element using javascript/jquery in Tampermonkey.
The class name and the tag of the elements are changing each time the page loads.
So I'd have to use some form of regex, but cant figure out how to do it.
This is how the html looks like:
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
The tag always is the same as the classname.
It's always a 4/5 letter random "code"
I'm guessing it would be something like this:
$('[/^[a-z]{4,5}/}')
Could anyone please help me to get the right regexp?
You can't use regexp in selectors. You can pick some container and select its all elements and then filter them based on their class names. This probably won't be super fast, though.
I made a demo for you:
https://codepen.io/anon/pen/RZXdrL?editors=1010
html:
<div class="container">
<abc class="abc">abc</abc>
<abdef class="abdef">abdef</abdef>
<hdusf class="hdusf">hdusf</hdusf>
<ueff class="ueff">ueff</ueff>
<asdas class="asdas">asdas</asdas>
<asfg class="asfg">asfg</asfg>
<aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>
js (with jQuery):
const $elements = $('.container *').filter((index, element) => {
return (element.className.length === 5);
});
$elements.css('color', 'red');
The simplest way to do this would be to select those dynamic elements based on a fixed parent, for example:
$('#parent > *').each(function() {
// your logic here...
})
If the rules by which these tags are constructed are reliably as you state in the question, then you could select all elements then filter out those which are not of interest, for example :
var $elements = $('*').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
DEMO
Of course, you may want initially to select only the elements in some container(s). If so then replace '*' with a more specific selector :
var $elements = $('someSelector *').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
You can do this in vanilla JS
DEMO
Check the demo dev tools console
<body>
<things class="things">things</things>
<div class="stuff">this is not the DOM element you're looking for</div>
</body>
JS
// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;
// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
var tagName = el.tagName.toLowerCase();
var classlistVal = el.classList.value.toLowerCase();
if (tagName === classlistVal) { return el; }
});
targets.forEach(function(el) {
// Do stuff
console.log(el)
})

jquery random element id for every loop

sorry i'm new in jquery and i need help :-(
i want to traverse all elements on html page with class parts
then go inside to two children and pass them a random number ( the same for them both)
for every element new random number is passed ( no repeat on page)
children classes are :
anot-head
anot-body
this is a sample code:
$(document).ready(function() {
$.each($('.parts'), function(){
var ran=Math.floor(Math.random()* 1000000);
$( ".anot-head" ).attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
$( ".anot-body" ).attr( "id","s"+ran );
});
});
$(".anot-body") does a search of the whole document, if you want to find a particular element in another element you need to do a search from that parent element.
In your case you would do a search on the particular .parts element that is currently being iterated over in your $.each() callback
$('.parts').each(function(index,element){
var parent = $(element);
var ran=Math.floor(Math.random()* 1000000);
parent.find('.anot-head').attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
parent.find('.anot-body').attr( "id","s"+ran );
});
No need to use random.... use index of each
$('.parts').each(function(index){
var $part = $(this);
$part.find('.anot-head').attr({"data-toggle":"collapse","href":"#s"+index});
$part.find('.anot-body').attr("id","s"+ index);
});

click all buttons on page except when parent has a specific class

I want to click all buttons on a page that have the attribute data-capture='noiseClicked'
This is my code so far:
javascript: (function() {
var followButtons = $("li.js-profile-card button[data-capture='noiseClicked']");
var index = followButtons.length - 1;
follow();
function follow() {
if (index >= 0) {
$(followButtons[index--]).click();
setTimeout(follow, 1);
}
}
})();
However I want to exclude buttons that have a parent of li.noise--active or li.friend--active
So the following would be clicked:
<li class="js-profile-card noise--active"><button data-capture="noiseClicked" type="button"></button></li>
but the following would not be clicked...
<li class="js-profile-card noise--active"><button data-capture="noiseClicked" type="button"></button></li>
or
<li class="js-profile-card friend--active"><button data-capture="noiseClicked" type="button"></button></li>
I thought that jquery's not selector would be helpful here, but I'm not sure how to use it to exclude a parent element with a specific attribute and I don't know how to exclude two different attributes (noise--active and friend--active)
Thanks.
You can use parent & hasClass methods for this:
var indexToSet = index--;
if( !$(followButtons[indexToSet]).parent().hasClass( 'noise--active' ) && !$(followButtons[indexToSet]).parent().hasClass( 'friend--active' )) {
$(followButtons[indexToSet]).click();
}
EDIT:
to travel up in the node list better to use closest() method:
var indexToSet = index--;
if( !$(followButtons[indexToSet]).closest( 'noise--active' ).length && !$(followButtons[indexToSet]).closest( 'friend--active' ).length ) {
$(followButtons[indexToSet]).click();
}
:not selector might come handy:
var followButtons = $("li.js-profile-card:not(.noise--active,.friend--active) button[data-capture='noiseClicked']");

How to use the element I check with .has() using jQuery

I was wondering how I could use the element that I check with .has() using jQuery.
This is what I have so far
HTML
<div>
<!--Only this paragraph should have a red background -->
<p>This is a paragraph</p>
<h1>This is not a paragraph</h1>
</div>
<div>
<h1>This is not a paragraph</h1>
</div>
jQuery
$("div").has("p").addClass("para");
As you can see, I ask if my div has a <p> and if so to add a class. My intention was to add the class to the paragraph but it seem to be that the class is added to my division. How can I add the class to my <p> after using $("div").has("p")?
I should put it in an if statement like this
if($("div").has("p")){
{...}.addClass("para");
}
but how can I add the class to my <p>?
I have a fiddle to make it clear
(I know I could use .each() for this problem but I want to know if it's possible with .has() too?)
simply you can use
$("div p").addClass("para");
While I recommend that you follow Mr. Aliens suggestion, if you absolutely must use .has() you have to first select the paragraph. When you write it like this:
$("div").has("p").addClass("para");
Your selected element is still the div(s).
If you want to avoid writing an If-statement, write the check this way:
$("div").has("p").find("p").addClass("para");
EDIT: This doesn't really check IF the div contains a paragraph, but rather selects the ones that have. The result is basically the same.
if($("div").find("p").length != 0) {
// another way to check if there is a p element inside of a div
$("div").find("p").addClass("para");
}
OR if you are not happy with this you can change jQuery's has function to this
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length,
has = false;
this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
has = true;
}
}
});
return has;
},
$("div").has("p").find('p').addClass('class_name');
// It will add class on p if div has p element

Javascript get class text inside element

I have a bunch of span4 class elements in my html. they look something like this:
<div class="span4">
<div class="widget">
<div class="header">blablabla</div>
</div>
</div>
I want to sort the span4 by that text iside header class.
I do this to sort them
$(".span4").sort(sortAlpha)
but how do I select the text inside the header class?
I'm doing this but I guess there is a better way
function sortAlphaAsc(a,b){
var nomeA = $(a.childNodes[1].childNodes[1]).text();
var nomeB = $(b.childNodes[1].childNodes[1]).text();
return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;
};
there must be a better way than
$(a.childNodes[1].childNodes[1]).text()
var elems = $(".span4");
elems.sort(function(a, b) {
return $(a).find('.header').text().toUpperCase().localeCompare(
$(b).find('.header').text().toUpperCase()
);
});
$(".span4").parent().html(elems);​
FIDDLE
Try this:
function sortAlphaAsc(a,b){
var nomeA = $(a).find('div.header').text();
var nomeB = $(b).find('div.header').text();
return nomeA.toLowerCase() > nomeB.toLowerCase();
};
You could detach the spans, sort and append them.
That will be very fast too as changing elements in memory and only updating the DOM once in the end is very efficient.
var $spans = $(".span4").detach();
var sortedSpans = $spans.sort(function(spanA, spanB) {
var spanTextA = $("div.header", spanA).text();
var spanTextB = $("div.header", spanB).text();
return spanTextA > spanTextB;
});
$("body").append(sortedSpans);
Obviously instead of body you append it back to it's actual container element.
Or if the spans are in a common container store the parent in cache var $parent = $spans.parent() and in the end simply do $parent.html(sortedSpans).
I don't know your whole mark-up but that should get you started.
DEMO - Detach spans, sort them and append again
Do you mean something like this:
$('.span4').find('.header').text();
This will return the text inside the header div.

Categories