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/
Related
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
I got several divs using classes like
.wrap-1-addon-1
.wrap-2-addon-1
.wrap-3-addon-1
I want to select all of them and use if ( $(this).hasClass() ) to check if its one of them. Currently I only do check for a single class. How can I check all of these, for example .hasClass('wrap-*-addon-1')?
Best regards.
You can combine two jquery Attribute Starts With Selector [name^=”value”] and Attribute Ends With Selector [name$=”value”] to do this work.
$('div[class^="wrap-"][class$="-addon-1"]')
$('div[class^="wrap-"][class$="-addon-1"]').css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap-1-addon-1">wrap-1-addon-1</div>
<div class="wrap-2-addon-1">wrap-2-addon-1</div>
<div class="wrap-3-addon-1">wrap-3-addon-1</div>
<div class="wrap-3-addon-2">wrap-3-addon-2</div>
You can use starts with selector:
$('div[class^="wrap"]')
JsFiddle demo
You could use .is() which support multiple classes, unfortunately .hasClass() works only for one class at a time.
Example:
element.is('.wrap-1-addon-1, .wrap-2-addon-1, .wrap-2-addon-1')
It is better to add another class and select with this class. You can then test it with regex.
$el = $(".wrap");
$el.each(function() {
var test = /wrap-[1-3]-addon-1/.test($(this).attr("class"));
$(".result").html(test);
console.log(test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap-1-addon-1 wrap"></div>
<div class="wrap-2-addon-1 wrap"></div>
<div class="wrap-3-addon-1 wrap"></div>
<div class="result"></div>
Inspiring regex matching from this answer:
var $ele = $("div:first");
alert(matchRule($ele.attr('class'),'wrap-*-addon-1'))
function matchRule(str, rule) {
return new RegExp("^" + rule.split("*").join(".*") + "$").test(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrap-1-addon-1">
</div>
<div class="wrap-2-addon-1">
</div>
<div class="wrap-3-addon-1">
</div>
This might help you, i used regex to resolve if current element's class(es) suits the desired pattern.
I assume you have more than 3 classes to check.
This pattern is for wrap-1-addon-1 to wrap-n-addon-1, n is some digit
function hasMyClass(elm) {
var regex = /(wrap-)+(\d)+(-addon-1)/i;// this is the regex pattenr for wrap-*-addon-1
var $this = $(elm);
var myClassesStr = $this.attr('class');
if(myClassesStr) { // if this has any class
var myClasses = myClassesStr.split(' '); // split the classes
for(i=0;i<myClasses.length;i++) { // foreach class
var myClass = myClasses[i]; // take one of classes
var found = myClass.match(regex); // check if regex matches the class
if(found) {
return true;
}
}
}
return false;
}
function test() {
$('#container div').each(function(){
var $this = $(this);
$('#pTest').append('<br/>test result for ' + $this.attr('id') + ':' + hasMyClass(this));
// hasMyClass(this) is the sample usage
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="div1" class="wrap-1-addon-1 anotherClass">div1 (wrap-1-addon-1)</div>
<div id="div2" class="wrap-2-addon-1 anotherClass anotherClass2">div2 (wrap-2-addon-1)</div>
<div id="div3" class="wrap-3-addon-1 anotherClass">div3 (wrap-3-addon-1)</div>
<div id="div4" class="anotherClass">div4 (none)</div>
</div>
<button id="testBtn" onclick="test();" type="button">TEST</button>
<p id="pTest" >...</p>
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>
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
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();