Get <div> elements without id in GWT - javascript

If i have html like this.Is there a way get a text apple between < div class="a" > and send it trought ajax to gwt application ?
<div class="A">
<div class="B">
<img class="icon" src="/images/ico.png" alt="" />
<div class="a">apple</div>
<div class="b">bannana</div>
</div>
</div>
and i have JavaScript like this :
$function(){
$('.B .icon').click(function(){
$(this).closest('.B').addClass('marked');
});
}

I would add this as a comment if I had enough reputation as I'm confused about your structure and question in general. Apologies if I don't understand correctly, but if you're typically traversing back up the DOM structure to the parent in your case could you use find to grab the element? .html() will grab the current content of said element.
$(function() {
$('.icon').click(function(){
var html = $(this).closest('.B').find('div.a').html();
// Do what you want with the contents. Simple alert as example.
alert(html);
});
});
This should get you what you're looking for. Please mark it as the answer if you find it matches what you need.
I'd suggest using .parent() rather than .closest('.B') if your elements will always be in the order you've posted and if further searching of the ancestor elements isn't needed.

Related

Right way to fill HTML from JS

I am currently working on a page that requires filling a div programmatically with a bunch of HTML like this sample code
<div id="Element">
<div class="tooltiptext top both">
<div class="editorMenuButton">
<span>Editor Menu</span>
<img src="https://github.com/..." />
</div>
<div class="diceButton">
<img src="https://github.com/..." />
</div>
</div>
</div>
right now, I am doing this as follows
Element.innerHTML = "<div class='tooltiptext top both'><div class='editorMenuButton'><span>Editor Menu</span><img src='https://github.com/...' /></div><div class='diceButton'><img src='https://github.com/...' /></div></div>";
which definitely works, but using a string to pass HTML seems like probably not the right/best/professional way to do it. Is there a better way?
Thanks!
Without involving any external libraries/frameworks, plain javascript allows you to create elements:
var mydiv = document.createElement('div');
see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement ]
You can add various properties as needed:
mydiv.className = 'tooltiptext top both';
see https://developer.mozilla.org/en-US/docs/Web/API/Element
Then append these created elements to other elements
Element.appendChild(mydiv);
see https://developer.mozilla.org/en-US/docs/Web/API/Element/append
There are several libraries that make this a bit easier such as metaflux
Well, in some cases make sense to use a string, but if you need something more structured, you may use document.createElement
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

How do I move these elements in DOM

I don't want to change HTML because I want to leave the display the way it is for default view and want to move them in second view. I want to know how I can dynamically order the class of a div.
I want to do this via button click. I have adEventListener() for 'click' where I am doing something and the move logic would go inside this event listener.
I understand that I can get these divs, remove from their parents and place it where I want. But I do not know how to do these for each of them since I have multiple lis. I am struggling with the loop so that I can do these for each li. I need to do this using pure JS and not jQuery.
<ul>
<li>
<div>
<div class="a">
<div class="b">
<a class="c">
<div class="d"></div>
<div class="e">
<div class="f"></div> // this is the first item that I want to move
</div>
<div class="g"></div> // this is the second item that I want to move
</a>
</div>
<div class= "h"></div> // I want above mentioned divs to be before this div
</div>
</div>
</li>
//There are multiples lis
<li></li>
Assuming you would like to do this on load of the page, you could solve your problem with the following JQuery DOM manipulations:
$(document).ready(function(){
$("ul .a").each(function(index, element){
$current_div_a = $(element);
$div_h = $current_div_a.find(".h");
$div_f = $current_div_a.find(".f");
$div_f.clone().insertBefore($div_h);
$div_f.remove();
$div_g = $current_div_a.find(".g");
$div_g.clone().insertBefore($div_h);
$div_g.remove();
})
});
You can test it out on this demo.
I strongly advise against this way of doing it though. I guess it's also the reason why your question got some downvotes too. Just modifying your HTML keeps your code clean, maintainable and clearer for anyone else starting to work on your project. Keeping backwards compatibility for your code as much as possible will cause maintainability problems later.
I ended up using
var list = document.querySelectorAll("ul li");
for (var item of list) {
let fClass = item.querySelector(".f");
fClass.parentNode.removeChild(fClass);
let parentOfFirstChildAfterWhichIwantMyF = item.querySelector(//selector for parentOfFirstChildAfterWhichIwantMyF);
parentOfFirstChildAfterWhichIwantMyF.insertAdjacentElement("beforeend", fClass);
}

passing variables on jquery

just having some issues with this jQuery thing.
What i'm trying to do is:
i have some audio control buttons that look like this:
<p>Play audio</p>
but there are too many on the page so i'm trying to optimise the code and make a little function that checks for the div id on the button and adds tells the player what track to play.
so i've done this:
<div id="audioControlButtons-1">
<div class="speaker"> </div>
<div class="play"> </div>
<div class="pause"> </div>
</div>
<script>
$(document).ready(function() {
$("[id^=audioControlButtons-] div.play").click(function() {
var id = new Number;
id = $(this).parent().attr('id').replace(/audioControlButtons-/, '');
//alert(id);
player1.loadAudio(id);
return false;
});
});
</script>
my problem is:
the id is not passing to the the player1.loadAudio(id)
if i hardcode player1.loadAudio(1)
it works! but the moment i try to pass the variable to the function it doesn't work...
however if you uncomment the alert(id) thing you will see the id is getting generated...
can someone help?
cheers,
dan
I think I see your problem. The variable id is a string. Try;
player1.loadAudio(parseInt(id));
Yah and the initialise line isn't necessary. Just use;
var id = $(this).parent().attr('id').replace(/audioControlButtons-/, '');
I'm actually kind of confused with your example because you originally have this:
<p>Play audio</p>
but then you don't reference it again. Do you mean that this html:
<div id="audioControlButtons-1">
<div class="speaker"> </div>
<div class="play"> </div>
<div class="pause"> </div>
</div>
Is what you are actually creating? If so, then you can rewrite it like this:
<div class="audio-player">
<div class="speaker"> </div>
<div class="play" data-track="1"> </div>
<div class="pause"> </div>
</div>
Then in your script block:
<script>
$(document).ready(function() {
$(".audio-player > .play").click(function() {
var track = $(this).data('track');
player1.loadAudio(+track);
return false;
});
});
</script>
So a few things are going on here.
I just gave your containing div a class (.audio-player) so that it's much more generic and faster to parse. You don't want to do stuff like [id^=audioControlButtons-] because it is much slower for the javascript to traverse and parse the DOM like that. And if you are going to have multiples of the same element on the page, a class is much more suited for that over IDs.
I added the track number you want to the play button as a data attribute (data-track). Using a data attribute allows you to store arbitrary data on DOM elements you're interested on (ie. .play button here). Then this way, you don't need to this weird DOM traversal with a replace method just to get the track number. This saves on reducing unnecessary JS processing and DOM traversing.
With this in mind now, I use jQuery's .data() method on the current DOM element with "track" as the argument. This will then get the data-track attribute value.
With the new track number, I pass that along into your player1.loadAudio method with a + sign in front. This is a little javascript trick that allows you to convert your value into an actual number if that is what the method requires.
There are at least a couple of other optimizations you can do here - event delegation, not doing everything inside the ready event - but that is beyond the scope of this question. Hell, even my implementation could be a little bit optimized, but again, that would require a little bit more in depth explanation.

Easiest way to get element parent

Suppose i have this structure of elements:
<div class="parent">
<div class="something1">
<div class="something2">
<div class="something3">
<div class="something4"></div>
</div>
</div>
</div>
</div>
And code like this:
$(".something4").click(function(){
//i could do it like this...
$(this).parent().parent().parent().parent().parent();
});
But that seems to be stupid, is there a better way to do this?
also i can't just say $(.parent) because there are many divs like this with class parent in my page.
Use .closest(selector). This gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
$('.something4').click(function() {
$(this).closest('.parent');
});
Use .closest():
$('.something4').click(function() {
$(this).closest('.parent');
});
I think you should try this
$(this).parents(".parent");
But I don't know where on the page are the other divs with this class :)
You could always use .parentNode (standard JavaScript). It's generally a bad idea to use class names that coincide with function/variable names from the library you're using (this goes for any language). Making your class names more unique is a better approach (for instance, "scparent" instead of "parent", if the name of your application was "Super Calculator" or something). This avoids conflicts such as the one you're describing.
I would caution using .closest(), simply because you may create a function like this:
function getParentElem() {
return $(this).closest('div');
}
And it would grab the parent div's in your code just fine, but if down the road you add a table for displaying data, and you run the function through a child element of the table, you will have to create another implementation that selects the table element, because that's what you now want:
<div id="tableParent">
<table id="dataTable">
<tr id="target1">
<td>Some data.</td>
</tr>
</table>
</div>
By using your function getParentElem() on the tr element, you'll end up grabbing the div with id="tableParent", rather than the actual parent, which is the table element. So, unless you've delineated your parent classes appropriately all the way through your code (which can be a pain and isn't always efficient), you may run into problems. Especially if at any point you're creating elements programmatically, or reading in data from another 3rd-party library or script.
Not saying it's not good to use .closest()... just pointing out a possible "gotcha".
i would suggest adding to the div parent an id like 'parent_1' etc. and in every son you keep the id in the rel attr
<div id="parent_1" class="parent">
<div rel="1" class="something1">
<div rel="1" class="something2">
<div rel="1" class="something3">
<div rel="1" class="something4"></div>
</div>
</div>
</div>
</div>
$(".something4").click(function(){
//i could do it like this...
$('#parent_' + $(this).attr('rel'));
});

jquery Remove siblings elements, doesn't work in IE7

I'm trying to remove all the sibling elements after a particular div, lets say the div tag with id = id8.
<form>
<div id="id5">something ...<div>
<div id="id8">something ...<div>
<div id="id3">something ...<div>
<div id="id97">something ...<div>
<div id="id7">something ...<div>
...
<div id="idn">some text ...<div>
</form>
To do that I use the following code in jquery.
$("#id8 ~ div").remove();
It works fine in Firefox, but It doesn't work in IE7.
Is there an alternative way to archieve this, using jquery and just giving the tag id from the element I want to start removing the elements?
Thanks
Thanks everybody for your help
I end up with this solution based on the accepted answer
function removeAfter(el,tag){
element = $('#'+el);
var aElements = $(tag,element.parent());
var index = (aElements.index(element));
for(i=(index+1);i<aElements.length;i++) {
$('#'+$(aElements.get(i)).attr('id')).remove();
}
}
just call
removeAfter('id8', 'div')
Two things!
1) Close your <div> tags! It should look like this:
<form>
<div id="id5">something ...</div>
<div id="id8">something ...</div>
<div id="id3">something ...</div>
<div id="id97">something ...</div>
<div id="id7">something ...</div>
<div id="idn">some text ...</div>
</form>
2) The ~ operator only matches siblings that follow the matched element (ie it will match id3, id97, id7 and idn, but not id5). To match every sibling, including id5, you do this:
$("#id8").siblings("div").remove();
That should leave you with just id8. I tested this in Firefox 3.5.5 and IE7.0something. Hope that helps!
Three steps here:
Find the index number of the element we've clicked, with respect to its parent.
Loop through all the div elements contained within this parent, starting after the one we just found
Delete each div found
$(document).ready(function(){
$('#parent').children().click(function(){
var index = ($('div',$(this).parent()).index(this));
for(i=(index+1);i<$('div',$(this).parent()).length;i++){
$($('div',$(this).parent()).get(i)).hide();
}
});
});
This will work on this HTML
<div id="parent">
<div id="c1">c1</div>
<div id="c2">c2</div>
<div id="c3">c3</div>
<div id="c4">c4</div>
<div id="c5">c5</div>
</div>
Comment here if you've got any more problems on the matter!
P.S. An application of this solution exact to your request is the following
function removeAfter(el){
element = $('#'+el);
var index = ($('*',element.parent()).index(element));
for(i=(index+1);i<$('*', element .parent()).length;i++){
$($('*', element.parent()).get(i)).hide();
}
};
EDIT:
Editing the answer below to add what should be a fix for the problem:
$("#id8").nextAll().remove();
END EDIT.
Ok. This appears to be an interesting bug - initial testing seems to indicate it's a jquery bug although I haven't found any specific mention of it anywhere.
The bug seems to be that if your initial selector tag is the same type as its siblings then it will fail to return any siblings in IE7.
I tested it using the jQuery example code for the selector itself and was able to duplicate your problem in IE8 emulating IE7.
If you check the jquery example code I'll stick below you can see that the actual element they're using as the initial selector is a span and the sibling elements are all divs whcih seems to me to indicate they know about this bug and haven't documented it, which is both cunning and shitty.
<script>
$(document).ready(function(){
$("#prev ~ div").css("border", "3px groove blue");
});
</script>
<div>div (doesn't match since before #prev)</div>
<span id="prev">span#prev</span>
<div>div sibling</div>
<div>div sibling <div id="small">div niece</div></div>
<span>span sibling (not div)</span>
<div>div sibling</div>
Change the #prev span to a div and you'll get the same failure as you're getting currently. I'd submit a bug with the jquery team.

Categories

Resources