How to find earlier element by partial id - javascript

I trying to find the parent div of a clicked item but can only get it working by manually setting the div id. There are many similar divs with incrementing id's
<div id="grid0"...
<div id="grid1"...
<div id="grid2"...
etc
My javscript is as follows but this only finds the first grid
function popUp1HtmlContent(e) {
var dataItem = $("div[id^=grid]").data("kGrid").dataItem(e.target.closest("tr"));
var content = dataItem.PopUp1Html;
return content;
}
How do I find the parent div in this function?
Eg setting this manually works for each grid
var dataItem = $("div[id=grid0]").data("kGrid").dataItem(e.target.closest("tr"));
var dataItem = $("div[id=grid1]").data("kGrid").dataItem(e.target.closest("tr"));
etc
Is there a way to search back through the parents to find the first matching div with id starting "grid{0}"?
The event fires from an image within a td element. Also it's not always the direct parent but can have varying number of elements between clicked element and div I'm trying to locate.

Related

Javascript: Get click target of arbitrary element within div tag

So, the situation is the following.
I have a div element which serves as a container for all kind of other elements (especially <a hre0="..."><img ...></img></a> and <iFrame> tags):
<div id="myDiv">
So basically, what i wanna do is to get the click target (if applicable) for all kind of elements within this div tag, under the assumption that there is always only one click with target specified.
Speaking UI wise: I want to see the target link that the user sees when he hovers with the cursor over the element.
Is there a generic approach to achieve this?
It sounds like what you want to do is find all the child elements of your wrapper div, then loop through them getting the 'href' property. Something like:
var children = document.getElementById('myDiv').children;
for (var i = 0; i < children.length; i++) {
var childElement = children[i];
var destination = childElement.href;
// do whatever you want with destination here. You can also get the associated IDs etc.
}
Untested but should work.

How to swap placement of two elements, including their classes/ids with onclick?

I'm trying to switch the positions of two divs with an onclick event.
The divs have the same basic format (width, height), but an additional class and id change the way they look.
So, I have two functions that successfully change the id and class names, but there is no visual change.
Here they are:
function whenClickedFilled(){
console.log("filled");
this.firstElementChild.id = "empty";
this.firstElementChild.className = "puzzlepiece emptyDivClass";
}
function whenClickedEmpty(){
console.log("empty");
this.firstElementChild.id = "filled";
this.firstElementChild.className = "puzzlepiece";
}
I'd like to know what the best way is to alternate between classes/ids onclick.
Here is my js fiddle.
I think what you're really looking to do is not swaping the class and id, but swap the elements themselves. This will make sure the numbers contained within the div's is also transfer with the swap.
You still need to implement the logic checks to see if the element should be able to swap with the empty block and there looks like theres a bug when you click empty space itself. But, this should get you on the right track. I recommend placing a debugger statement to step through the code with dev tools open. It will help understand whats taking place. Good luck.
function whenClickedFilled(){
console.log("filled");
//Get the div element and parent
//Then determine the parent of the empty div
var clickedDiv = this.firstChild; //this refers to the TD clicked, get the child div element
var clickedDivParent = this; //this is TD
var emptyDivParent = emptyDiv.parentElement; //stored the empty div reference into a global, retrieve the parent as this could change
//Remove the empty and clicked div's from their container
emptyDivParent.removeChild(emptyDiv)
clickedDivParent.removeChild(clickedDiv);
//Add the elements back to the containers but swapped
clickedDivParent.appendChild(emptyDiv);
emptyDivParent.appendChild(clickedDiv);
}
http://jsfiddle.net/tWrD2/
I'm trying to switch the positions of two divs with an onclick event
If you want to swap two adjacent nodes, you can do something as simple as:
function swapAdjacent(el0, el1) {
el0.parentNode.insertBefore(el1, el0);
}
If you want to swap any two elements in the DOM, you can do something like:
// Swap the postion in the DOM of el0 and el1
function swapElements(el0, el1) {
// Create a temp node that can replace el0
var tmp = el0.cloneNode(false);
// Replace el0 with tmp
el0.parentNode.replaceChild(tmp, el0);
// Replace el1 with el0
el1.parentNode.replaceChild(el0, el1);
// Replace temp node with el1
tmp.parentNode.replaceChild(el1, tmp);
}
and some test markup:
<div id="d0">div 0</div>
<div id="d1">div 1</div>
<button onclick="
swapElements(document.getElementById('d0'), document.getElementById('d1'));
">Swap d0, d1</button>
<button onclick="
swapAdjacent(document.getElementById('d0'), document.getElementById('d1'));
">Swap adjacent</button>
Of course the two elements to swap must be consistent with the surrounding elements, e.g. you can't swap an option element with a div and expect everything to work, but you can probably swap a span with a div.
If you want to swap elements by clicking on one or the other:
<div id="d0" onclick="swapElements(this, document.getElementById('d1'))">div 0</div>
<div id="d1" onclick="swapElements(this, document.getElementById('d0'))">div 1</div>
I found a nice solution provided by fuell when I was searching fo an actual html swap:
<div id="div_1">THIS IS DIV 1</div>
<div id="div_2">THIS IS DIV 2</div>
Go Swap!
$(document).ready(function() {
$(".go-swap").click(function() {
$("#div_1").removeAttr("style");
$("#div_2").removeAttr("style");
var tmp = $("#div_1").html();
$("#div_1").empty().append($("#div_2").html());
$("#div_2").empty().append(tmp);
});
});

get the div parent element of a clicked element, in order to get the p class in the same div

I have a div that looks like this:
<td id="monday">
<p class="outter">whatever here</p>
<p class="hidden" style="display:none">Some content I want to get</p>
</td>
Now the problem is - the td id will change (this is just one of many).
So what I'm trying to do, is when a user clicks on the .outter (it'll always be called outter), I want to find the td id, in order to then get access to the p class (which will always be 'hidden').
So I've tried this (document.body is to get round a dynamic loading problem I had):
$(document.body).on('click', '.outter', function() {
var info = $(this).parent("td").$(".hidden").text();
$("#rightBox").css("width", "200px");
$("#rightBox").css("background", "#f0f0f0");
$("#rightBox").empty();
$("#rightBox").append(info);
});
The issue I am having is in the very first line, getting the variable.
I want to say this particular .outter class, find it's parent, then find the hidden class within it. Then get the text within that hidden class. Then take that variable and dump it into #rightBox;
Can anybody help?
The line var info = $(this).parent("td").$(".hidden").text(); throws an error, you should use find or children method, as the target element is a next direct sibling of the clicked element, you can use next method, you don't need the ID of the parent element.
$(document.body).on('click', '.outter', function() {
// var info = $(this).closest('td').find('.hidden').text();
var info = $(this).next('.hidden').text();
$("#rightBox").css({"width": "200px", "background": "#f0f0f0"})
.html(info);
});
Note that you can also create a class and use addClass method instead of css method, this makes your code a little cleaner.
You can do like this:
$(document.body).on('click', '.outter', function() {
var info = $(this).next().text();
$("#rightBox").css("width", "200px");
$("#rightBox").css("background", "#f0f0f0");
$("#rightBox").empty();
$("#rightBox").append(info);
});
Demo: http://jsfiddle.net/eMzcx/

Toggling elements with JavaScript

I want to toggle a div element (expand/collapse) when clicked.
I have many div elements, on click to new element, I want to collapse the previous one and expand the current clicked one.
I tried using static type variable to save the instance of previous div tag and compared with the current selection, but I don't know why is it not working.
Searching about this, I got similar code idea to collapse all div and then expand the current selected only, but I want to just toggle the previous one with new one, not collapse all div and expand the selected (though I would be using it if other way is not possible)
Can it be done using static variables of js?
At its simplest, you can simply do something like this:
var divs = document.getElementsByTagName('div'),
collapseClass = 'collapsed',
current = divs[0];
// Hide all elements except first, add click event hander
for(var i = 0, len = divs.length; i < len; i++){
divs[i].onclick = function(){
if(this !== current){
toggle(this, current);
current = this;
}
};
if(i > 0) toggle(divs[i]);
}
This will store the current element in a variable, then toggle it when another element is clicked. It also uses an if statement to check if the currently clicked element is the one currently visible element, and only toggles if its not.
See a working demo of this here: http://jsfiddle.net/GaxvM/
You can assign a unique ID to each of the elements and use document.getElementById to identify both elements, and then collapse one/expand the other.
If you number them sequentially (like div1, div2, div3, etc) you could do something like:
function colexp(div_id){
div_2_collapse = document.getElementById(div_id);
next_div = div_id.substr(0,3) + parseInt(div_id.substr(3))+1;
div_2_expand = document.getElementById(next_div);
hide(div_2_collapse);
show(div_2_expand);
}

javascript JQuery printing to multiple divs on page load?

I basically have several divs each with ids "id_1", "id_2" "id_3" etc. The divs are all initially empty.
I want on page load to populate all the divs with certain html content. But the part that has been troubling me is that I also need to extract the unique id portion for use within the html:
<div id="id_3">
<div id="inner_3></div>
</div>
where the inner div is what gets printed. Notice that the '3' is extracted from the container div id by the javascript and then subsequently used and printed in the inner div.
Any ideas how to do this with jquery? Thanks in advance.
You can fetch all the div elements that have an id that starts with a certain string:
$(function() {
$('div[id^=id_]').each(function() {
var id = $(this).attr('id').split('_').pop();
$(this).html(
$('<div/>').attr('id','inner_' + id)
);
});
});
Then you loop through each, get the id, and do your HTML manipulation.
there are several ways of doing this, but in the end its just simple string manipulation. Here is an example:
// on page load
$(function(){
//find all divs and iterate through them - you can use any selector you like
$("div").each(function(){
//this gets the id attribute of the div we are currently on in the loop
var id = $(this).attr("id");
//this gets the number at the end - notice that its just string manipulation
var nid = id.slice(id.lastIndexOf("_") + 1)
//create inner div, give it an id and append
var innerDiv = $('div').attr("id", "inner_" + nid);
$(this).append(innerDiv);
//all done - you can append content to inner div here
// innerDiv.append(someContent);
});
});

Categories

Resources