I have a list of div on a parent function, each does a onclick function.
How can I make a function that I can have a function to get the first div and run the onclick function?
The important thing is, my divs can be sorted. So after being sorted, the "first div" might not be the first anymore, so I need a function to be defined and each time when window is ready I run it once, and after the divs are sorted I run it again.
Thanks!
Edit: OK, say here's my code, I will sort those divs based on the id:
<div id="e">
<div id="e1" onclick="$(this).siblings().removeClass('someclass').addClass('someclass')">Something</div>
<div id="e2" onclick="$(this).siblings().removeClass('someclass').addClass('someclass')">Something</div>
<div id="e3" onclick="$(this).siblings().removeClass('someclass').addClass('someclass')">Something</div>
<div id="e4" onclick="$(this).siblings().removeClass('someclass').addClass('someclass')">Something</div>
<div id="e5" onclick="$(this).siblings().removeClass('someclass').addClass('someclass')">Something</div>
</div>
Use delegate with first selector.
$("divsContainer").delegate("div:first", 'click', function(){
});
Note: Specify the appropriate selector for divsContainer which is actually the contianer in which all these divs are present.
Use jquery to select all the divs on the page (or within any container containting these sortable divs). This will give you an array. Take the first element, and it will be first div.
$('#parent div:first-child').click();
do you mean something like this ?
$('#idOfParentDiv div:first').click();
Related
Let's say there are several similar elements like:
<div id="element_01" class="element" data-id="01" data-color="blue">
Some content
</div>
<div id="element_02" class="element" data-id="02" data-color="yellow">
Some content
</div>
<div id="element_03" class="element" data-id="03" data-color="green">
Some content
</div>
With an AJAX call I have to get a new entire element, including all attributes of it and replace one of the elements above with it. The loaded element could look like this:
<div id="element_02" class="element active" data-id="02" data-color="red">
Some NEW content
</div>
As you can see, it is actually the same as element_02 in the original group, but with another content, an additional class and with a different data-color value. The desired result should look like this:
<div id="element_01" class="element" data-id="01" data-color="blue">
Some content
</div>
<div id="element_02" class="element active" data-id="02" data-color="red">
Some NEW content
</div>
<div id="element_03" class="element" data-id="03" data-color="green">
Some content
</div>
I know how to load the contents of an element into another element, which would be:
$('#element_02').load(url+' > *');
But that loads, as mentioned, only the contents into the element and leaves the classes and the data attributes alone.
Of course, I could manually just add the new class to the element and change the data value manually after the load with a function, like so:
$('#element_02').load(url+' > *', function(){
$('#element_02').addClass('active');
$('#element_02').data('color', 'red');
});
But I was wondering if there is a more universal approach which takes care of all the parent attributes without manually having to add or change them.
My idea would be like.
Create temporary div
load entire element into temporary div
copy contents of temporary div and insertAfter target element
remove temporary div
remove the original/target div
Would something like that work without big hickups and glitches while loading?
Maybe someone has a solution for this. Thanks.
I have now indeed managed to solve it myself with the suggested idea. Probably not perfect, but works.
function ReplaceElementCompletely(id) {
$('.element[data-id="'+id+'"]').addClass('remove_this');
$('<div class="temporary"></div>').insertAfter('.element[data-id="'+id+'"]');
$('div.temporary').load(url+' .element[data-id="'+id+'"]', function(){
$('.temporary > .element').insertBefore('.temporary');
$('.temporary').remove();
$('.remove_this').remove();
});
}
ReplaceElementCompletely('02');
I have this situation:
<div id="first">
<div>
<p>text</p>
</div>
</div>
<div id="second">
<div>
<button class="button">click</button>
</div>
</div>
...
<div id="first"> ... </div>
<div id="second"> ... </div>
...
and so on, the structure repeats.
This structure is created dynamically so I can't use any specific class nor id for the first div.
I need to retrieve the text in the first div when I hit the button in the second div.
(NOTE: I need a pure javascript solution, not a jQuery solution)
Thanks
Assuming you have an event handler for the button click, you could do this from that event handler:
function buttonClickHandler(e) {
var first = this.parentNode.parentNode.previousSibling;
var paragraphs = first.getElementsByTagName("p");
var text = paragraphs[0].textContent;
}
If you have common and known class names on the the divs marked first and second, then you can make your Javascript code much more insulated from markup changes which is generally a good idea.
P.S. I presume you know that you should't have duplicate id values in your HTML. This code doesn't use them, but you should be using class names instead of id values if you're going to have duplicates.
I am using this div code
<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>
and trying to print the values like
japp.init = function () {
console.log($("div").data("role"));
console.log($("div").data("lastValue"));
console.log($("div").data("hidden"));
console.log($("div").data("options").name);
});
This works fine if I put the above div tag directly inside body but as I put the div tag inside any other div tag it does not work and says undefined.
<div class="page">
<div data-role="page" data-last-value="43" data-hidden="true" data- options='{"name":"John"}'></div>
</div>
console prints undefined for above html.
Please let me know if anything is not clear
When getting data jQuery returns data from the first element matching selector, if the first div in DOM has no data - jquery won't return it.
try
japp.init = function () {
console.log($("div[data-role]").data("role"));
console.log($("div[data-lastValue]").data("lastValue"));
console.log($("div[data-hidden]").data("hidden"));
console.log($("div[data-options]").data("options").name);
});
or better give this div an id, and select by id like $('#someid').data('role')
Your selector is div and when you have more divs on your page jQuery will select (in this case) the first one.
<div class="page">
<div data-role="page" data-last-value="43" data-hidden="true" data- options='{"name":"John"}'></div>
</div>
In the above HTML the first div does not have data-* so it will result with an undefined value
You have to be more specific with your selectors
$('.page div').data('role')
Or
$('div:first div').data('role')
Try
$("div.page div").each(function(){
console.log($(this).data("whatever_you_need"));
});
etc.
This way you will cycle through all divs nested in div with class 'page'.
You aren't exactly specifying which div to get. Whenever you are trying to get specific data from a specific element, you should be sure which div you are accessing. This can either occur within an iteration of elements or by ID or an element in relation to an ID. It shouldn't be done based on tagname or even classname as they can be multiple. In this case, why not add an ID on the div you are trying to get so you can access it specifically:
<div class="page">
<div id="thisDiv" data-role="page" data-last-value="43" data-hidden="true" data- options='{"name":"John"}'></div>
</div>
Then access:
console.log($("#thisDiv").data("role"));
Also, it is bad for performance to wrap the same jquery object over and over, you can cache it like this:
$thisDiv = $("#thisDiv");
console.log($thisDiv.data("role"));
....
I believe it is because $("div") returns all occurrences of div and then selects the first to perform a function on. I'm not sure how you want to use this functionality but it might be worth considering something like this
JSFiddle where a class is used to select the correct div
$(function(){
console.log($(".div").data("role"));
console.log($(".div").data("lastValue"));
console.log($(".div").data("hidden"));
console.log($(".div").data("options").name);
});
give your Div a class like class="myClass"
<div class="page">
<div class="myClass" data-role="page" data-last-value="43" data-hidden="true" data- options='{"name":"John"}'></div>
</div>
and then you can change your jquery selector:
japp.init = function () {
console.log($(".myClass").data("role"));
console.log($(".myClass").data("lastValue"));
console.log($(".myClass").data("hidden"));
console.log($(".myClass").data("options").name);
});
otherwise jquery don't know which div you are looking for.
I hope this will help
I have several div as following:
<div id='id1'>blabla</div>
<div id='id2'>blabla</div>
<div id='id3'>blabla</div>
<div id='id4'>blabla</div>
<div id='id5'>blabla</div>
<div id='id6'>blabla</div>
And I would like to add a new div (<div id='newdiv'>) in order to wrap the div I specify.
For example before 'id3' and after 'id5'.
So we obtain:
<div id='id1'>blabla</div>
<div id='id2'>blabla</div>
<div id='newdiv'>
<div id='id3'>blabla</div>
<div id='id4'>blabla</div>
<div id='id5'>blabla</div>
</div>
<div id='id6'>blabla</div>
Do you know jQuery code to do this?
Use jQuery .wrapAll() :
$('#id3, #id4, #id5').wrapAll('<div id="newdiv" />')
Fiddle : http://jsfiddle.net/K4HVR/
Probably a simple plugin to make it more flexible, reusable:
$.fn.customWrap = function (end, wrapperDivAttr) {
this.nextUntil(end).next().addBack().add(this).wrapAll($('<div/>', wrapperDivAttr));
}
$('#id3').customWrap('#id5', { id: 'newDiv'}); // call the function on the startelement, specify the end elements selector and attribute obj.
nextUntil to get all the divs until the end div, then next to select the end div as well, and addback() to add the previous elements (nextUntil ones) to the collection and then add() to select the start div as well and then wrapAll of them.
Demo
In a bit of a hurry so this is untested but something like this?
$("#id3, #id4, #id5").wrapAll('<div id="newdiv" />');
EDIT: Oh damn, looks like Karl-André beat me to it!
I'm using the following HTML structure:
<div id="clock">5:30 AM
<div id="day">Wednesday
</div>
<div id="date">14 December
</div>
</div>
I update the contents of these elements using Javascript. For "day" and "date" I use $("#day").text(day) and $("#date").text(date). Because "clock" is a parent element I had to use $("#clock").prepend(clock) to succesfully add the text.
The problem with the latter function, is that new text is prepended every time the clock is refreshed, i.e. it builds up a list of clock times. For the first two functions the text is just replaced, like it should. Is there a way to make this happen for the "clock" function as well?
EDIT: Sorry, should have been a bit more clear about the clock. Have edited the code, so you understand. BTW, the reason the clock is parent element is that could make the other two elements depend on the clock's position and styling.
I also created a jsFiddle: https://jsfiddle.net/daanodinot/NZtFA/
I left the list building thing (annoyingly) in!
BTW, I'm not too sure if function(); setInterval('function()', 1000) is the best way to refresh, so if you something better I'd be happy to know :)
What you need to do is change the structure of your html to this.
<div id="wrapper">
<div id="clock"></div>
<div id="day"></div>
<div id="date"></div>
</div>
Then for the javascript
$('#clock').text('12:45');
$('#day').text('Wednesday');
$('#date').text('12/14/2011');
This way you can just change/refresh the text of clock instead of prepending values to it.
Another approach, with your current html, which i do not recommend.
<div id="clock">
<div id="day">
</div>
<div id="date">
</div>
</div>
The js
$('#clock').contents().get(0).nodeValue = '12:45';
$('#day').text('Wednesday');
$('#date').text('12/14/2011');
If you have HTML
<div id="clock">
<div id="day"></div>
<div id="date"></div>
</div>
Then you don't have to modify #clock at all. By doing $("#day").text(day) and $("#date").text(date) content of those divs is changed and you don't have to touch #clock.
But in case you want to replace a content of a element then use .html(newContent). See documentation.
You should first add a new element with prepend and then replace it's content, now you just constantly keep prepending new elements instead of working on the same element again.
What do you mean by
Because "clock" is a parent element I had to use
$("#clock").prepend(clock) to succesfully add the text.
?
It seems redundant. Since $('#day') and $('#date') uniquely address your targeted elements.
My tip:
Do not use clock. $("#day").text(day) and $("#date").text(date) already update the numbers inside your #clock element.
Hy,
my consideration for your problem is, IF you choose to manipulate the Content of the #clock div you could simply do this:
var newContent="";//in here comes whatever you want to add to your clock div
$('#clock').html($('#clock').html()+newContent);
That's the way I use it most of the time but you could also do this:
var curContent=$('#clock').html();
curContent+="<>put in your code to add</>";
$('#clock').html(curContent);
This is I guess a bit slower than the first one, but it works.