I want to add a specific DIV to other DIVs of a defined class. Because the page changes regularly I do this on every DOM-Change. This happens quite often and there are a lot of DIVs (up to a few 1000) that meet the criteria.
(This is an extension so I cannot modifiy the source)
I do it this way:
$('.Qg').each(function() {
if ($(this).parent().find('.quickShare').length === 0)
{
$(this).before('<div class="quickShare">(some more html)<br/></div>');
}
});
That works but does not seem to be very performant, mainly because of the "each" - Loop
Is there a more elegant (and especially performant) way to get only those DIVs which's parent do not contain my DIV (something like $('.Qg').parent().without('quickShare').each(function(){}); (pseudocode)?
Update: To make it clearer a DOM-Example:
<div class="anOuterDiv>
<div class="Qg">something here</div>
</div>
<div class="anotherOuterDiv">
<div class="quickShare">already added</div>
<div class="Qg">something here</div>
</div>
I want to Add the "quickShare" div before the "Qg", but only if it does not exist. (So I want to get the upper Qg, but not the lower Qg)
Give all the parents of .Qg the class QgContainer, then do:
$(".QgContainer:not(:has(.quickShare)) > .Qg").each(function() {
...
});
Since you can't change the site, try:
$(".Qg").filter(function() {
return $(this).siblings(".quickShare").length == 0);
}).each(function() {
...
});
As you wanted better(more perfomant) then you could consider using pure Javascript.
HTML
<div class="anOuterDiv1">
<div class="Qg">something here</div>
</div>
<div class="anOuterDiv2">
<div class="quickShare">already added</div>
<div class="Qg">something here</div>
</div>
<div class="anOuterDiv3">
<div class="Qg">something here</div>
</div>
<div class="anOuterDiv4">
<div class="quickShare">already added</div>
<div class="Qg">something here</div>
</div>
Javascript
Array.prototype.forEach.call(document.getElementsByClassName('Qg'), function (Qg) {
var parentNode = Qg.parentNode,
quickShares = parentNode.getElementsByClassName('quickShare'),
newQuickShare;
if(!quickShares.length) {
newQuickShare = document.createElement('div');
newQuickShare.className = 'quickShare';
newQuickShare.textContent = 'Newly added';
parentNode.insertBefore(newQuickShare, Qg);
}
});
On jsFiddle
Next we should actually compare it against some jQuery, so we will use the accepted answer.
$(".Qg").filter(function() {
return $(this).siblings(".quickShare").length == 0;
}).each(function() {
$(this).before('<div class="quickShare">Newly added</div>');
});
On jsFiddle
And now lets see how they perform on jsPerf
You can filter each .Qg that's not preceded by a .quickShare sibling and then apply .before() on that:
$('.Qg')
.filter(function() {
var node = this.previousSibling; // start with previous sibling
while (node) {
if (node.className == 'quickShare') {
return false; // we found one
}
node = node.previousSibling; // keep trying with previous sibling
}
return true;
})
.before('<div class="quickShare">(some more html)<br/></div>');
This time it will definitely work:
$('div:only-child.Qg').each(function(){
$(this).before('<div class="quickShare">(some more html)<br/></div>');
});
Try this. This is very easy and readable and small and performant.
jsFiddle Demo http://jsfiddle.net/VS6mG/
Related
Hi i have to find the "findme" div in dom structure after a particular div
and find the first instance after the div using one Jquery.
following may be the dom structure:
ex1:
<div class="abc"></div>
<div class="findme"></div>
ex2:
<div class="abc"></div>
<div>
<div class="findme"></div>
</div>
ex3:
<div>
<div class="abc"></div>
</div>
<div>
<div class="findme"></div>
</div>
ex4:
<div>
<div class="abc"></div>
</div>
<div class="findme"></div>
above are some examples of dom structure in which i want to find "findme" first div after "abc" div using jquery
i tried using after(),closest().nextAll().first()
but i am not getting the query to match above all examples .
so please can anyone help me to find the div first element ("finme") after "abc" div
I want find the next "findme" div in complete dom after "abc" div and first occurrence of after "abc" div above are some examples the dom can be
The only way I could find to get this to work for all cases is to walk the entire DOM sequentially with a filter:
var foundAbc;
$('*').filter(function() {
if ($(this).hasClass('abc')) {
foundAbc = true;
} else {
if (foundAbc && $(this).hasClass('findme')) {
foundAbc = false;
return true;
}
}
return false;
}).css('color','red');
JSFiddle: https://jsfiddle.net/TrueBlueAussie/LnLf79od/2/
You could wrap this behavior in a jQuery extension method if you wanted to make it reusable.
$.findNext = function(selector1, selector2) {
var foundAbc;
return $('*').filter(function() {
if ($(this).is(selector1)) {
foundAbc = true;
} else {
if (foundAbc && $(this).is(selector2)) {
foundAbc = false;
return true;
}
}
return false;
});
}
and use like this:
$.findNext('.abc', '.findme').css('color', 'red');
JSFiddle: https://jsfiddle.net/TrueBlueAussie/LnLf79od/3/
i've got this function as per below:
$(".selectedItems").on('click', '.deleteItem', function (event) {
$(this).parent().remove();
if ($(this).parent('.selectedItems').children().length === 0) {
alert('hello');
}
});
in conjunction with the following html:
<div class="selectedItems">
<div class="item">
</div>
<div class="item">
</div>
</div>
<div class="selectedItems">
<div class="item">
</div>
<div class="item">
</div>
</div>
The problem is that the size is always showing up as 0 regardless and my if statement keeps on triggering, i been looking at this code for a while.. im not sure about what can be the problem.
You can find a link to the jsfiddle here: http://jsfiddle.net/kmcbride/UpGgQ/6/
As mentioned in comments, you have already removed the element and therefore $(this).parent() no longer refers to anything.
Try storing the parent first:
var $parent = $(this).parent(), $selItem = $(this).parents(".selectedItems");
$parent.remove();
if( $selItem.children().length === 0) {
alert("Hello!");
}
Updated Fiddle
change the selector like this,
$(this).parents('.selectedItems').children().length
also you are removing the parent $(this).parent().remove();.
change that too
Demo
You need to first save a count of how many items there are before you remove the item from the DOM. Otherwise the reference to the DOM is lost.
http://jsfiddle.net/thinkingmedia/zXnDa/
$(".selectedItems").on('click', '.deleteItem', function (event) {
var count = $(this).closest(".selectedItems").find(".item").length;
$(this).closest(".item").remove();
if (count == 1) {
alert('hello');
}
});
So I have a mini slide menu in my website there is a menu you can choose what you want to read. There are points to click, when u clicked it the point get a red background.
But there is a problem.
When i click one point and then an other point the first clicked point have to lose his background.
Here is my HTML:
<div id="slide_button" onClick="clicked(this);"><dir class="button_1"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_2"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_3"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_4"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_5"></dir></div>
Here is my JS:
function clicked(slide_button) {
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
HERE IS AN EXAMPLE ON FIDDLE.
My "QUESTION IS" what i have to do to solve that?
What should I pay attention?
First you need to fix your HTML becaue your id values aren't unique. In fact, you don't even need id values, so you should use "slide_button" as a class. You can then use it to select all the buttons:
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
The CSS needs to be changed now so "slide_button" is a class selector, instead of an id selector:
.slide_button {
display: inline-block;
}
As for clearing the background, clear all of them before coloring the selected one red:
function clicked(slide_button) {
var buttons = document.getElementsByClassName('slide_button');
for(var i = 0; i < buttons.length; i++) {
buttons[i].getElementsByTagName('dir')[0].style.backgroundColor = '';
}
slide_button.getElementsByTagName('dir')[0].style.backgroundColor = 'red';
}
jsfiddle
This uses just JavaScript with no JQuery, but if you are using JQuery, you might as well use it here. The code is a lot shorter and easier to follow.
Here's a JQuery version:
$(function() {
$('.slide_button').click(function() {
var $button = $(this);
$button.children(':first').css({ backgroundColor: 'red' });
$button.siblings().children(':first').css({ backgroundColor: '' });
});
});
Note: This registers a click-handler, so you can get rid of the "onclick" attirbutes.
jsfiddle
You have to select all other points and set their background to none.
Or remeber which point is selected and on select another just remove background on last and remeber current point, then set its background to red.
See fiddle: http://fiddle.jshell.net/399Dm/5/
At first id should be unique per element.
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
Second, you should store reference of clicked element if you want later remove background color, and instead of inline event handlers or binding all elements would be better if you use event delegation.
Demonstration
(function () {
"use strict";
// getting parent node of divs, due to bind click event. then
var ele = document.querySelector(".slide_button").parentNode,
prev = null; // store previous clicked element
ele.addEventListener("click", clickHandler); // event handler.
function clickHandler(e) {
var t = e.target; // get target of clicked element
// filter by target node name and class. edit: removed class checking
if (t.nodeName.toLowerCase() === "dir") {
// checking value of prev !== null and it's not same element.
if (prev && prev !== t) {
prev.style.backgroundColor = "";
}
prev = t; // store clicked element
t.style.backgroundColor = "red";
}
}
}());
I have fixed the fiddle so that it works hopefully as you plan.
http://jsfiddle.net/399Dm/8/ There you go!
var forEach = function(ctn, callback){
return Array.prototype.forEach.call(ctn, callback);
}
function clear(element, index, array) {
element.getElementsByTagName("dir")[0].style.backgroundColor="";
}
function clicked(slide_button) {
forEach(document.getElementsByClassName("slide_button"), clear);
//.style.backgroundColor="";
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
I had a slightly different method than #atlavis but a similar result.
http://fiddle.jshell.net/2AGJQ/
JSFIDDLE DEMO
jQuery
$('.slide_button').click(function(){
$('.slide_button dir').css("background-color", "inherit");
$(this).find('dir').css("background-color", "red");
});
HTML - Your markup is invalid because you have duplicate ids. Make them classes as below instead.
<div class="slide_button" >
<dir class="button_1"></dir>
</div>
<div class="slide_button">
<dir class="button_2"></dir>
</div>
<div class="slide_button">
<dir class="button_3"></dir>
</div>
<div class="slide_button">
<dir class="button_4"></dir>
</div>
<div class="slide_button">
<dir class="button_5"></dir>
</div>
CSS change
.slide_button {
display: inline-block;
}
If you can look at the following jsfiddle, I used jQuery to get what you want.
I am trying to figure out if there is a way around doing .hasClass() multiple times to see if the active element I am working with has one of currently four specific classes, I am also trying to figure out the most optimized way to do this while the element(s) that are acting as the trigger (or the active element) has multiple classes in it mostly for styling purposes.
Example of the HTML:
<div class="form_row">
<div class="primary_row">1</div>
</div>
<div class="form_row">
<div class="primary_row subexists">1</div>
<div class="primary_row_sub">1a</div>
</div>
<div class="form_row">
<div class="primary_row subexists">1</div>
<div class="primary_row_sub subexists">1a</div>
<div class="secondary_row">2</div>
</div>
<div class="form_row">
<div class="primary_row subexists">1</div>
<div class="primary_row_sub subexists">1a</div>
<div class="secondary_row subexists">2</div>
<div class="secondary_row_sub">2a</div>
</div>
I am in the progress of currently building it up, so this is still a rough draft, but its safe to assume more classes will exist on various elements per the need. The Four main classes I am worried about are primary_row, primary_row_sub, secondary_row, secondary_row_sub. I am building a click handler like:
$('.form_row > div').click(function()
{
//code
});
in this click handler I want to be able to detect if the element clicked is one of the four mentioned above. Where if it is, I want to do something based on which. So determining which class is of the element clicked, rather than building four click handlers one for each type. I am hoping I can keep it optimized and contained to a single handler. Any ideas?
One option:
var classMap = {"one": function () { alert("one");},
"two": function () { alert("two");},
"three": function () { alert("three");}
}
, classes = "";
$('div').click(function (e) {
classes = this.className.split(" ");
for (key in classMap) {
if ($.inArray(key, classes) !== -1) {
classMap[key]();
}
}
});
http://jsfiddle.net/wp9X7/5/
if ($(this).is(".primary_row")) {
...
} elseif ($(this).is(".primary_row_sub")) {
...
} and so on
Is there any jQuery function similar to closest() that will return elements outside of the parent chain, traversing sideways? For example, I want to call a function foo() on the div source that would return the div target. I know I could navigate using parent() and siblings(), but I need something generic that would go as many levels as needed, up, sideways and down?
var allsources = $('.source');
allsources.click(function()){
$(this).closest('.target').hide();
});
<div class="row">
<div>
<div class="target" ></div>
</div>
<div>
<div>
<div class="source"></div>
</div>
</div>
</div>
<div class="row">
<div>
<div class="target" ></div>
</div>
<div>
<div>
<div class="source"></div>
</div>
</div>
</div>
EDIT:
My definition of closest: you have an element source. Try to find it down. If find more than one, return one that is less node hoops down/next/prev. If not found, go one level up, and try to find again. Repeat until no parent.
If, by closest, you mean "travel up as little as possible, then anywhere downwards", then you can do
$("#source")
.closest(":has(.target)")
.find(".target:first") //make sure we only select one element in case of a tie
In your case, it would be better to specify the common parent directly:
$(this)
.closest(".row")
.find(".target") //there's no tie here, no need to arbitrate
This is a tricky one. As has been commented, how do you define closest in this context? Assuming you can decide on some rules; for example:
Traverse up: 3pt
Traverse down: 2pts
Move sideways: 1pts
And then consider the item with the lowest points to be "closest" then it would be easy enough to author a plugin, named something such as closestAll, which would do the recursive traversal of the whole dom tree to determine the closest item.
However, looking at your recent edit, one (of many!) right solutions to the problem stated is:
var allsources = $('.source');
allsources.click(function(){
$(this).parents('.row').find('.target').hide();
});
Live example: http://jsfiddle.net/zCvJM/ (Source A only hides Target A, Same for B)
If you know exactly the structure of the dom and level of nesting, have you consider to use the eq() method
$(this).parents().eq(1).prev().children(".target")
I don't think there is a way to do this other than basically querying the whole DOM:
$('#target')
Because if you want to go up and across (never mind down as well) then the target element isn't related to the child element. If you also want to check for the presence of the child element you will have to do that separately.
-Edit:
After reading your comment on wanting to find the closest element regardless of whether it is a parent, I think you will have to write a custom function to crawl back up the dom one node at a time. I have tested the following and it works:
Markup
<div id="parent">
<div id="child1">
<div id="source"></div>
</div>
<div id="child2">
<div class="target" rel="right"></div>
</div>
<div id="child3">
<div>
<div class="target" rel="wrong"></div>
</div>
</div>
</div>
Script
$(document).ready(function () {
var tgt = findClosest($('#source'), '.target');
if (tgt != undefined) {
alert(tgt.attr('rel'));
}
});
function findClosest(source, targetSel) {
var crawledNodes = $();
var target = null;
// Go up
source.parents().each(function () {
console.log(crawledNodes.index($(this)));
if (crawledNodes.index($(this)) == -1 && target == null) {
crawledNodes.add($(this));
target = findTarget($(this), targetSel);
// Go across
$(this).siblings().each(function () {
console.log("Sibling");
if (crawledNodes.index($(this)) == -1 && target == null) {
crawledNodes.add($(this));
target = findTarget($(this), targetSel);
}
});
}
});
return target;
}
function findTarget(el, targetSel) {
console.log(targetSel);
var target = el.find(targetSel);
if (target.size() > 0) {
return target.eq(0);
}
else
{
return null;
}
}
If I understood the specification correctly you mean something like the function closest defined below:
var allsources = $(".source");
function closest($source,selector) {
if($source == null) return $([]);
var $matchingChildren = $source.find(selector);
if($matchingChildren.length != 0) return $($matchingChildren.get(0));
else return closest($source.parent(), selector)
}
allsources.click(closest($(this),'.target').hide();});
You can see it working at http://jsfiddle.net/y2wJV/1/
Your definition requires that when choosing among matching children the function must return one that is less node hoops down/next/prev. This requirement has not been met, but this function is quite flexible and seems to do what you want to do in the case of the example you provided.
I found this code that is simple but does not solve the tie issue (returns the first)...
(function ($) {
$.fn.findClosest = function (filter) {
var $found = $(),
$currentSet = this; // Current place
while ($currentSet.length) {
$found = $currentSet.find(filter);
if ($found.length) break; // At least one match: break loop
// Get all children of the current set
$currentSet = $currentSet.parent();
}
return $found.first(); // Return first match of the collection
};
})(jQuery);
I encountered a similar problem, i had a table i needed to find the next element which may be outside the current td, so i made a jquery function:
$.fn.nextAllLevels = function(sel) {
if ($(this).nextAll(sel).length != 0) {
return $(this).nextAll(sel).eq(0);
} else if ($(this).nextAll(':has(' + sel + ')').length != 0) {
return $(this).nextAll(':has(' + sel + ')').find(sel).eq(0);
} else {
return $(this).parent().nextAllLevels(sel);
}
So to use this you simply call
$('#current').nextAllLevels('.target');
To give you the element closest in the foward direction, regardsless of whether in is in the current parent or not.