How to remove elements except any specific id - javascript

let say there is a parent id which contains many elements and i want to remove all elements except one.
ex. :
<div id = "parent_id">
<div id = "id_1">
<div id = "id_11"> </div>
<div id = "id_11"> </div>
</div>
<div id = "id_2"> </div>
<div id = "id_n"> </div> // No need to remove this id_n only
</div>
As i can remove innerHTML like this document.getElementId('parent_id').innerHTML = ''; but i need not to remove id_n. is there any way to do that using javascript or jQuery.

$("#parent_id").children(":not(#id_n)").remove();

$("#parent_id > :not(#id_n)").remove();

No jQuery required:
const parent = document.querySelector('#parent_id');
const keepElem = document.querySelector('#id_n');
[...parent.children]
.forEach(child => child !== keepElem ? parent.removeChild(child) : null);

I think the Attribute Not Equals selector makes sense here.
$("#parent_id div[id!='id_n']").remove();
Demo.

For fun, POJS is a tad more code, but no jQuery :-)
var p = document.getElementById('parent_id');
var d = document.getElementById('id_n');
p.innerHTML = '';
p.appendChild(d);
A lot faster too. ;-)

Deleting all children other than id_n with jQuery:
$('#parent_id div').not('#id_n').remove();
If you'are going to delete the parent_id as well:
$('#id_n').insertAfter('#parent_id');
$('#parent_id').remove();

Related

Changing content in multiple classes via JS

I want to change the HTML-value of the highlighted span below (class=percent-value):
<div id="verfuegbarstd" class="et_pb_number_counter_4" data-number-value="0" data-number-separator="">
<div class="percent">
<p>**<span class="percent-value">0</span>**<span class="percent-sign"></span></p>
</div>
<h3 class="title">Verfügbare Stunden</h3>
<canvas height="0" width="0"></canvas>
</div>
I tried the following:
var verfuegbareStd = document.getElementsByClassName('et_pb_number_counter_4').getElementsByClassName('percent').getElementsByClassName('percent-value');
var budget = document.getElementsByClassName('et_pb_number_counter_2').getElementsByClassName('percent').getElementsByClassName('percent-value');
var lohnProStd = document.getElementsByClassName('et_pb_number_counter_3').getElementsByClassName('percent').getElementsByClassName('percent-value');
var gebrauchteStd = document.getElementsByClassName('et_pb_number_counter_5').getElementsByClassName('percent').getElementsByClassName('percent-value');
function calcVerfuegbareStd() {
var calc = budget.innerHTML / lohnProStd.innerHTML;
verfuegbareStd.innerHTML = calc;
}
calcVerfuegbareStd();
Does that make any sense?
document.getElementsByClassName returns a collection of all elements in the document with the specified class name, as a NodeList object. So thats why i check the length.
You can use also document.querySelector which gets the first element in the document with the class "xxxx" is returned.
I put both!
You can do it with jquery also but i thought you want pure js.
var elements = document.getElementsByClassName('percent-value'); // List of elements
var spanQuery = document.querySelector('.percent-value'); // The first element in the document with the class "myclass" is returned:
spanQuery.innerHTML = 'Hello!!!';
if (elements.length > 0) {
var span = elements[0];
span.innerHTML = 'Hello!!!';
}
<div id="verfuegbarstd" class="et_pb_number_counter_4" data-number-value="0" data-number-separator="">
<div class="percent">
<p>**<span class="percent-value">0</span>**<span class="percent-sign"></span></p>
</div>
<h3 class="title">Verfügbare Stunden</h3>
<canvas height="0" width="0"></canvas></div>
Try this?:
document.getElementsByClassName("percent-value").innerHTML = "the content you want";
It is simpler to use querySelector(). This will return the first element.
var verfuegbareStd = document.querySelector('.et_pb_number_counter_4 .percent .percent-value');
console.log(verfuegbareStd.innerHTML)
<div id="verfuegbarstd" class="et_pb_number_counter_4" data-number-value="0" data-number-separator="">
<div class="percent">
<p>**<span class="percent-value">0</span>**<span class="percent-sign"></span></p>
</div>
<h3 class="title">Verfügbare Stunden</h3>
<canvas height="0" width="0"></canvas>
</div>

JS Remove all elements except a specific ID and its children

Responses to this:
How to remove elements except any specific id
are close to what I want but not quite.
In my case I am asking how I can remove all elements under parent id except id_n and its children: test1 and test2. The elements need to be removed, not just hidden.
<div id = "parent_id">
<div id = "id_1">
<div id = "id_11"> test</div>
<div id = "id_12">test </div>
</div>
<div id = "id_2"> test</div>
<div id = "id_n">id_n<br>
<div id='test1'>test1<br><div>
<div id='test2'>test2<br><div>
</div>
</div>
The result should be:
<div id = "parent_id">
<div id = "id_n">id_n<br>
<div id='test1'>test1<br><div>
<div id='test2'>test2<br><div>
</div>
</div>
Thanks for looking at this. Your suggestions are appreciated.
Using jQuery's siblings you remove all of it's children:
$('#id_n').siblings().remove();
Okay after thinking about this, there is another approach using Array manipulation:
var parentElement = document.getElementById('#parent_id');
parentElement.innerHtml = [].splice.call(parentElement.children).filter(item, function() {
return item.id === childId;
}).reduce((collatedHtml, item, function() {
return collatedHtml + item.innerHtml;
});
This grabs all the direct children of the parentElement and returns a new array (using Array.filter) before using Array.Reduce to collate the innerHtml of all the children.
Note: the reason i'm not using the ... prefix to convert to an Array is because it is not supported in IE 11 and below

How to iterate through all div and get specific property?

what I'm trying to do is iterate over a collection of div, contained in a parent container. My structure is the following:
<div id='main'>
<div data-id='2'>
</div>
<div data-id='3'>
</div>
</div>
My goal is take the field data-id of each div and create an array collection. Previously I used the select where do I get each value of available option, like this:
var available_services = $('#selected-service').find('option', this).map(function ()
{
return this.value;
}).get();
But now I'm using a div collection instead of the select. How I can iterate through all available div?
This should return all data-id values in a list:
var available_services = $('#main').find('div').map(function (item)
{
return item.attr('data-id');
});
I didn't test this, but I think should do the job. (maybe you need to tweak a little bit)
I believe this will do it:
var available_services = [];
$('#main div').each(function(){
available_services.push($(this).data( "id" ));
})
This is the easy way to go:
$(document).ready(function() {
var myCollection = [];
$('#main div').each(function(){
var dataDiv = $(this).attr('data-id');
myCollection.push(dataDiv)
})
});
Try this:
(function(){
var main = $("#main");
var divs = $(main).find("div");
var arrId = divs.map(function(index, div){
return $(div).attr("data-id");
});
console.log(arrId);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='main'>
<div data-id='2'>
</div>
<div data-id='3'>
</div>
</div>

How to find an element by data attribute with find() function?

I add a data attribute to an element via jquery data() function.
I want to use find() function to get the element. But obviously, it does not work.
What I want to do is caching the element's parent element and do a lot of things.
Like this:
var $parent = $('#parent');
var $dataElement = $parent.findByData('whatever');
$parent.xxx().xxx().xxx()....;
I don't want this:
var $parent = $('#parent');
var $dataElement = $("#parent [data-whatever='whatever']");
$parent.xxx().xxx().xxx()....;
//It looks like find the parent twice.
Can any function do this?
I add a data attribute to an element via jquery data() function.
As you mentioned you are setting the data to the element with data() method of jQuery. Which doesn't adds any attribute in the DOM. So you can't find it with .find() that way because it's in memory*.
Instead you should use .attr() method to set the data attribute and then you can read it from the DOM with .find() method.
* don't have proper word for it
below is an example of setting the data with .data() and trying to find it.
$('#parent').find('.two').data('test', 'myTest');
var div = $('#parent').find('.child[data-test="myTest"]').length;
alert(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<div class='child one'></div>
<div class='child two'></div>
</div>
below is an example of setting the data with .attr() and trying to find it.
$('#parent').find('.two').attr('data-test', 'myTest');
var div = $('#parent').find('.child[data-test="myTest"]').length;
alert(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<div class='child one'></div>
<div class='child two'></div>
</div>
below is an example as per your comment:
$('#parent').find('.two').data('test', 'myTest');
var div = $('#parent').find('.child').filter(function(){
return $(this).data('test') == 'myTest'
}).text();
console.log(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<div class='child one'>One</div>
<div class='child two'>Two</div>
</div>
You can try $(child,parent) way and attribute selector $('[attribute-name]') as parameter,
var $parent = $('#parent');
var $dataElement = $parent.children().filter(function(){
return $(this).data('whatever') !== undefined
});
If you need a function findByData(),
$.fn.findByData = function(dataAttribute){
return $(this).children().filter(function(){
return $(this).data(dataAttribute) !== undefined
});
}
var $parent = $('#parent')
var $dataElement = $parent.findByData('whatever');
Fiddle Demo
If you want to get the parent element only when it has data attribute value equals to somevalue, you need to use filter function:
$parent.filter(function(){
return $(this).data('whatever') == "whatever"
});
If you want to find child element of parent that has data attribute value equals to somevalue:
$parent.find("*").filter(function(){
return $(this).data('whatever') == "whatever"
});;
<div id="parent">
<p data-whatever='whatever'>Whatever1</p>
<p data-whatever='whatever'>Whatever2</p>
<p data-whatever='whereever'>Whereever1</p>
</div>
var $parent = $('#parent');
var $dataElements = $parent.find("*[data-whatever='whatever']");
This will return an array of decedent elements inside the "#parent" element having data-whatever='whatever'.
$.each($dataElements,function(key,val){
console.log( $($dataElements[key]).html());
});
Demo

How to wrap multiple divs

example,
<div id = "test1">test1</div>
<div id = "test2">test2</div>
i want to wrap a parent div like this,
<div id="parent_test">
<div id = "test1">test1</div>
<div id = "test2">test2</div>
</div>
I tried to use jquery wrap(), but it only wraps one by one:(
You need wrapAll:
$("#test1, #test2").wrapAll($("<div>", { id: "parent_test" }));
jsFiddle
use .wrapAll():
$('#test1,#test2').wrapAll('<div id="parent_test" style="color:red;"></div>');
Working Demo
Use jQuery WrapAll method
<div id = "test1" class="my-div">test1</div>
<div id = "test2" class="my-div">test2</div>
$('.my-div').wrapAll("<div class='my-wrap'></div>");
http://jsfiddle.net/6eGuG/

Categories