Get div id's of all divs with a specific class - javascript

I am trying to get div ids of all div elements having a specific CSS class.
I am able to get [object HTMLDivElement] by using getElementByClass but I haven't been able to get id from this object.
Basically, entirely I want to do is
get div ids of all div elements that have a specific CSS class,
get data-title of all div elements,
match data-title of these div elements with a string,
make display:none of all non-matching div elements.
Here is what I have tried:
function FilterFiles(filterItem) {
var elements = document.getElementsByClassName("listItem");
for (var i = 0; i < elements.length; i++) {
alert(elements[i].id);
// get div id of divs with data-title !=(not equal) filterItem
// make display:none of matching divs
}
}
Here is the Fiddle with actual HTML http://jsfiddle.net/6bo1rjrt/1/.

var temp = new Array();
var title = new Array();
function FilterFiles(filterItem) {
$('.listItem').each(function ()
{
temp.push($(this).attr("id")); //get id of each div to array
alert($(this).attr("id"));
title.push($(this).attr("data-title")); //get title of each div to array
if($(this).attr("data-title") != filterItem) //check non matching div
{
$(this).hide(); //hide div
}
});
}
first u loop throught all div with specific class with each, then check it's "data-title".

You can use attribute-not-equal-selector for that. also you need to give ids to div elements:
function FilterFiles(filterItem) {
var ids= $('.listItem[data-title!="'+filterItem+'"]').map(function(){
return this.id;
}).get()
}
Working Demo
For hiding elements that do not have data-title value equal to:
$('.listItem[data-title!="'+filterItem+'"]').hide()

Using Jquery, you can do the following:
var arr = [];
$('.listItem').each(function(){
arr.push($(this).attr('id'));
});

Using jQuery .each():
var arr = [];
$('.listItem').each(function(){
arr.push(this.id);
});
Using jQuery .map()
var arr = $('.listItem').map(function() { return this.id; }).get();

I modified your fiddle example. see this updated fiddle
$("#filter").click(function () {
var filterItem = "A03-5(KAB製ヒーター付エアサスオペシート)_20140515154904.xlsx";
FilterFiles(filterItem);
});
function FilterFiles(filterItem) {
var elements = $("div.listItem");
elements.each(function(){
var el=$(this);
if(el.data("title")!=filterItem)
el.hide();
else
el.show();
});
/*for (var i = 0; i < elements.length; i++) {
alert(elements[i].id);
// get div id of divs with data-title !=(not equal) filterItem
// make display:none of matching divs
}*/
}

Related

select html element by its full html tag - JS

I am looking for a way to be able to select an HTML element by its tag, like:
document.querySelector("<div id='myDiv'\>hello world</div\>")
//instead of: document.querySelector("#myDiv")
However, this code returns an error. The code should return the HTML element.
Does anybody know a way to achieve this? (vanilla JS preferred)
It seems a bit odd that you wouldn't want to select element via ID. But regardless one way of selecting the element in your example would be to look for its innerHTML.
e.g
var div = document.getElementsByTagName('div');
for (var i=0;i<div.length;i++){
console.log(div[i].innerHTML)
if(div [i].innerHTML == 'hello world'){
var element = div[i].parentElement
console.log(element)
break;
}
}
You could use outerHTML to search for it, however this only works if the element has a parent element.
var els = Array.from(document.querySelector('body *')); //this selects all elements in the body
var el;
for(var i = 0; i < els.length; i++) {
if(els.outerHTML === "<div id='myDiv'\>hello world</div\>") {
el = els[i];
}
}
//Use the el variable for your element

get the all the id's from a class when the image is selected

I have few uploaded images in one div and I want to move them to another div and update the database table. For that I need the id's of the images selected and the name of the div where I want to move.
I have the id of the selected image using the check box but I am not sure how can I get all id's in the end .
function MoveImages(){
for ( var i = 0; i < $(".ct input[type=checkbox]:checked").length; i++) {
var element = $(".ct input[type=checkbox]:checked")[i];
var parent = element.parentNode;
var id = parent.getAttribute('id');
}
}
how can I get all the id's in the end ?
This is how my class looks like.
<div class="ct" id="559429bc0d559162552c9728">
<input type="checkbox" class="remove">
<img src="/image?id=c9728" data-src="random.JPG" id="previewImagec9728">
</div>
the move function should return all the id's.
With a bit of JQuery's $.each, substring, and JS array methods, you can grab the raw IDs and put them in an array like so:
var ids = [];
//For each element that matches ".ct input[type=checkbox]:checked".
$.each($('.ct input[type=checkbox]:checked'), function() {
//Find the image element, get the id value, and strip the first 12 characters.
var id = $(this).find('img').attr('id').substring(12);
//Put ID in array.
ids.push(id);
});
Use $.map():
var yourIds = $(".ct input[type=checkbox]:checked").map(function(){
return $(this).parent().attr('id');
});
Try jquery's each:
$('.ct').each(function() {
var id = $(this);
})
use :has and .map
$('.ct:has(:checked)').toArray().map(function(element, index) { return element.id })
or
$('.ct:has(:checked)').map(function(index, element) { return element.id }).toArray()
in both cases .toArray() is to get a normal array instead of a jquery array

Apply CSS on matching text

I am trying to apply a class where text matches with sibling elements.
My certain condition is:
I have a table with multiple rows based on data that I get through database.
One of the td elements has my defined class.
Now I wanted to apply a class only on those td elements where the text of this element matches with another one.
So It would be like, td's whose html/text is equal has that class.
I tried:
$('#table tbody>tr').find('td[class^="customtd"]').each(function() {
if($(this).html().trim() == $(this).siblings('td').html().trim()) {
$(this).addClass('active');
}else {
$(this).removeClass('active');
}
});
You'd have to iterate each sibling td (or use filter), check for a text match, then add the class:
$('#table tbody>tr').find('td[class^="customtd"]').each(function() {
var text = $(this).text();
$(this).siblings("td").filter(function() {
return $(this).text() == text;
}).addClass("active");
});
You have to set the value you are searching for and then loop through all table data. If you find a match, add the certain class.
Furthermore you should cache variables in jQuery and avoid using each() function since its performance is really bad compared to for loops.
//cache the element you are searching for
var search = $('.customtd').html().trim();
//cache the whole table so we can use a for loop
var table = $('#table tbody>tr>td');
//use for loop for more performance
for (var i = 0; i < table.length; i++) {
if(table.eq(i).html().trim() == search) {
table.eq(i).addClass('active');
}else {
table.eq(i).removeClass('active');
}
}
Here is a working example:
http://jsfiddle.net/jnh2heuh/2/

How to reduce 180 lines of code down to 20 in Javascript?

I have a lot of click handler functions which are almost (textually and functionally) identical. I've got a menu with maybe 10 items in it; when I click on an item, the click handler simply makes one div visible, and the other 9 div's hidden. Maintaining this is difficult, and I just know there's got to be a smart and/or incomprehensible way to reduce code bloat here. Any ideas how? jQuery is Ok. The code at the moment is:
// repeat this function 10 times, once for each menu item
$(function() {
$('#menuItem0').click(function(e) {
// set 9 divs hidden, 1 visble
setItem1DivVisible(false);
// ...repeat for 2 through 9, and then
setItem0DivVisible(true);
});
});
// repeat this function 10 times, once for each div
function setItem0DivVisible(on) {
var ele = document.getElementById("Item0Div");
ele.style.display = on? "block" : "none";
}
Create 10 div with a class for marking
<div id="id1" class="Testing">....</div>
<div id="id2" class="Testing">....</div>
<div id="id3" class="Testing">....</div>
and apply the code
$('.Testing').each(function() {
$(this).click(function() {
$('.Testing').css('display', 'none');
$(this).css('display', 'block');
}
}
$(document).ready(function (){
$("div").click(function(){
// I am using background-color here, because if I use display:none; I won't
// be able to show the effect; they will all disappear
$(this).css("background-color","red");
$(this).siblings().css("background-color", "none");
});
});
Use .siblings() and it makes everything easy. Use it for your menu items with appropriate IDs. This works without any for loops or extra classes/markup in your code. And will work even if you add more divs.
Demo
Fiddle - http://jsfiddle.net/9XSJW/1/
It's hard to know without an example of the html. Assuming that there is no way to traverse from the menuItem to ItemDiv - you could use .index and .eq to match up the elements based on the order they match with the selector.
var $menuItems = $("#menuItem0, #menuItem1, #menuItem2, ...");
var $divs = $("#Item0Div, #Item1Div, #Item2Div, ...");
$menuItems.click(function(){
var idx = $(this).index();
// hide all the divs
$divs.hide()
// show the one matching the index
.eq(idx).show();
})
Try
function addClick(i) {
$('#menuItem'+i).click(function(e) {
// set nine divs hidden, 1 visble
for( var j = 0; j < 10; ++j ) {
var ele = document.getElementById("Item"+j+"Div");
ele.style.display = (i == j ? "block" : "none");
}
});
}
// One click function for all menuItem/n/ elements
$('[id^="menuItem"]').on('click', function() {
var id = this.id; // Get the ID of the clicked element
$('[id^="Item"][id$="Div"]').hide(); // Hide all Item/n/Div elements
$('#Item' + id + 'Div').show(); // Show Item/n/Div related to clicked element
});
Obviously this would be much more logical if you were using classes instead:
<elem class="menuItem" data-rel="ItemDiv-1">...</elem>
...
<elem class="ItemDiv" id="ItemDiv-1">...</elem>
$('.menuItem').on('click', function() {
var rel = $(this).data('rel'); // Get related ItemDiv ID
$('.ItemDiv').hide(); // Hide all ItemDiv elements
$('#' + rel).show(); // Show ItemDiv related to clicked element
});
Save the relevant Id's in an array - ["Item0Div", "Item1Div", ...]
Create a generic setItemDivVisible method:
function setItemDivVisible(visible, id) {
var ele = document.getElementById(id);
ele.style.display = visible ? "block" : "none";
}
And set your click handler method to be:
function(e) {
var arrayLength = myStringArray.length;
for (var i = 0; i < idsArray.length; i++) {
setItemDivVisible(idsArray[i] === this.id, idsArray[i]);
}
}
I think this will do the trick

How to push, pop, and wrap values in jQuery?

I've looked high and low and can't figure this one out!
On a page, I have links that have a certain class (plmore). On the same page, I have divs that have a certain class (fcontainer) among others. The number of links with the class plmore will always equal the number of div using the fcontainer class.
My question:
I need to wrap the divs that have fcontainer class with the links found using plmore.
PSEUDOCODE:
GET ARRAY OF HREFS
GET ARRAY OF DIV IDS
WRAP DIVS WITH HREFS
This is what I have so far:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
var hrefs = new Array();
$('a.plmore').each(function() {
hrefs.push($(this).find('a').attr('href'));
});
var features = new Array();
$('fcontainer').each(function() {
features.push($(this).find('div').attr('id'));
});
/* how does one pop from both arrays and wrap?? */
});
</script>
You mean like
jQuery(function ($) {
//find all the target anchor elements
var $as = $('a.plmore');
//find the div elements
$('.fcontainer').each(function (idx) {
//wrap the div at index idx using the href value of anchor element at index idx
$(this).wrap($('<a/>', {
href: $as.eq(idx).attr('href')
}))
});
});
Demo: Fiddle

Categories

Resources