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

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

Related

How to get the id of this div based upon search the inner html value?

How do I get the div id based upon the value "IBC-CW1 -DE-02A"
<div id="main">
<div id="hotspot1" class="drawing" data-canvas-width="89.91394117538998" style="left: 1397.52px;top: 1071.92px;font-size: 10.7966px;font-family: monospace;transform: scaleX(1.01043);background-color: #ff0000;">IBC-CW1 -DE-02A</div>
</div>
If i use parentnode means I am getting id="main"
How do i get hotspot1
Update:
var spot.hotspot_hover = "IBC-CW1 -DE-02A"
$(".textLayer").each(function(){
$('.drawing').css('background-color','transparent');
if($(this).html().indexOf(spot.hotspot_hover) > -1){
var cont_redirect = $(this).parent()
console.log(cont_redirect[0])
$(cont_redirect).css('background-color','#ff0000');
$('#content-wrapper').animate({scrollTop: cont_redirect[0].offsetTop+300},'slow');
}
});
Now I have to give background color for that content
Try the follwing jquery code
var divId = $("div.drawing:contains('IBC-CW1 -DE-02A')").attr('id');
console.log(divId);

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

Find the index of an element in an array created by toArray in JS/JQuery

I have a bunch of spans of class = "change" and each has a unique id. I created an array of those spans using:
var changesArray = $('.change').toArray()
I want to be able to get the index of the span in the array when I click on it. I tried:
$('.change').click(function(){
var thisChange = $(this).attr('id');
var thisChangeIndex = $.inArray(thisChange,changesArray);
});
But all I get is -1 for every .change I click on.
I'm a bit of a newbie with this type of code. Help?
The toArray method says
Retrieve all the elements contained in the jQuery set, as an array.
You are looking for a particular id in the array - that will never work.
If you want the index of the item you can use .index()
$('.change').click(function(){
var thisChangeIndex = $('.change').index(this);
console.log(thisChangeIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="change">change1</span>
<span class="change">change2</span>
<span class="change">change3</span>
<span class="change">change4</span>
</div>
<div>
<span class="change">change5</span>
<span class="change">change6</span>
<span class="change">change7</span>
<span class="change">change8</span>
</div>
You should keep a plain array of the unique ID's only:
var changesArrayIds = $('.change').toArray().map(function(x) { return x.id; });
Then this line should work fine:
var thisChangeIndex = $.inArray(thisChange, changesArrayIds);
If you insist on using .toArray that works http://codepen.io/8odoros/pen/JKWxqz
var changesArray = $('.change').toArray();
$('.change').click(function(){
var thisChange = $(this).attr('id');
var thisChangeIndex = -1;
$.each( changesArray, function( i, val ) {
if( thisChange==val.id) thisChangeIndex= i;
});
console.log(thisChangeIndex);
});
When you call toArray, you get an array of all the DOM nodes, not the jquery objects. You can search on this instead of $(this):
var changesArray = $('.change').click(function(){
var thisChangeIndex = $.inArray(this,changesArray);
}).toArray();

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 remove elements except any specific id

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

Categories