I have the following HTML code :
<div id="someId">
<div ng-transclude>
</div>
</div>
Really simple I am getting the div element which has ID attribute using the following function :
var getElementById = function (id) {
return angular.element("#" + id);
};
Where in this example case the ID is 'someId'. My goal is to get the div inside the one I just got. So I want to return the div with ng-transclude attribute. I believe that this will happen by getting an element by attribute name or something.
Thanks in advance.
PS: I can't put any other attributes in the div I wanted(like id) because in the real life it is far more complecated and the code is auto-generated.
I think this will help you
var getElementByAttribute = function (attribute) {
return angular.element(document).find('[' + attribute + ']');
};
var el = getElementByAttribute('ng-transclude')
I don't know if that will be the Angular way, but you can use native properties of the HTML element. Something like this:
var getElementById = function (id) {
return angular.element("#" + id);
};
var childDivWithTransclude = getElementById('someId').children[0];
Related
So I more than one dynamicly generated elements with the same class name that I am trying to check input for in jQuery. Instead of it letting me click on both, it is just letting me click the first element generated.
Ex: I click on item_1 and it returns the item_1 id, but when I click on item_2 it doesn't return anyting.
HTML
<div id="item_1" class="resp"></div>
<div id="item_2" class="resp"></div>
JS - Jquery
$(".resp").on("click",() =>{
var id = $(".resp").attr("id");
console.log('attempting toggle' + id);
});
Firstly, you have to use normal function instead of arrow function (to avoid missing the context). Secondly - use this keyword to refer to the actually clicked element.
$(".resp").on("click", function() {
console.log('attempting toggle ' + this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">A</div>
<div id="item_2" class="resp">B</div>
This is because .attr('id') returns the value of the id attribute of the first matched element in the set.
Instead, use an old school function for the handler so the this value is equal to the clicked div, then get its id:
$(".resp").on("click", function() {
var id = $(this).attr('id');
console.log('attempting toggle ' + id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">First</div>
<div id="item_2" class="resp">Second</div>
What you're doing here is referencing the classname to obtain the id. This gathers the id of the first classname, which isn't what you desire. What you need to do is use the this keyword to correctly obtain the id.
After removing the arrow function and changing the internal code a bit, it should look like this:
$(".resp").on("click", function() {
var id = this.id;
console.log('attempting toggle: ' + id);
});
Also make sure you've correctly installed JQuery. Pick up your JQuery embed code from here.
Also remember to include your JQuery code before your JavaScript code.
Ok so I want to .map() the src values of the html content of #stage to the variable srcArray
var content = $('#stage').html();
var srcArray = $.map($(content), function(el) {
return {value: $(el).children().attr('src')};
});
but when I console.log the array, each src value comes up as undefined. Anyone know what's up?
html is
<div id="stage">
<div style="left:xxx, top:xxx">
<img src="xxxxx" style="width:xxx, height:xxx"/>
</div>
</div>
Do I need to convert the src value to a string to have it show up on the chrome console?
You could get all the img from the #stage element.
var srcArray = $('#stage').find('img').map(function() {
return { value: $(this).attr('src') };
}).get();
Problem :
1. statement return {value: $(el).children().attr('src')}; Will execute for each children of 'div#stage' but stage also have a
div which doesn't have any src attribute.
2. In case 'div#stage'have multipleimg` elements then above statement will return only one result
3. Statement $(content) creating new html elements .Never create new content if you just want to treverse (A bad practice).
Solution :
1. Filter children so that only img tag will be selected.
2. Map on children('img') so that if there are more than 1 img element,code will be executed for each img
3. Use $('#stage') instead of $(content) (which is creating new html elements)
Try this-
var content = $('#stage').html();
var srcArray = $.map($(content).children("img"), function (el) {//better way use $.map($('#stage').children("img"), function (el) {
return {
value: $(el).attr('src')
};
});
console.log(JSON.stringify(srcArray))
Update:-
DEMO
Well the issue is with your children() selection and reading the attribute. It will read the attribute of the first child. So if the first child does not have the attribute it will be undefined. So you need to actually select the element you want. It is also weird you are selecting the html and than building a nodeset based on that html. Just do the selection and use map
var srcArray = $('#stage [src]').map(
function () {
return { value: $(this).attr('src')};
}
);
I currently have the following:
$(window).load(function(){
$(".boxdiv").click(function () {
$(this).toggleClass("selected");
});
});
Which perfectly does the first part of what I need. I have a fair amount of div's with the class "boxdiv" and they each have a unique ID that will identify it. What I need to happen is to have some kind of button that when pressed sends all of these div ID's with the class selected, to the next page.
Anyone got any idea of how I can do this?
Map the ID's in an array, and use $.param to create a querystring
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;});
window.location.href = '/next_page?' + $.param({ids : id_arr});
});
EDIT:
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
window.location.href = '/next_page?ids=' + qs;
});
Perhaps this is what you're looking for:
$(".button").click(function(){
var id_arr = [];
$(".boxdiv").each(function(){ // Loop through each element with that class
id_arr.push($(this).attr('id'));
}); // Loop through each element with that class
});
window.location = 'next.html/ID=' + id_arr.join(',');
The ID's should be stored in id_arr
You can loop over each div that has the class selected. You can then use attr() to access the ID names.
Javascript
var ids = [];
$.each($(".selected"), function() {
ids.push($(this).attr('id'));
});
ids = ids.join(',');
HTML
<div id="boxA"></div>
<div id="boxB" class="selected"></div>
<div id="boxC" class="selected"></div>
<div id="boxD"></div>
This should return ["boxB", "boxC"]
See: http://jsfiddle.net/B4V28/1/
All of the answers submitted are in fact correct - but I think the real issue is your expectation of what jQuery is doing for you.
jQuery will gather all of the ID's in any manner, but you will need to have a way to collect them on the next page and actually do something with them. This will all need to happen server side.
Most likely, the ideal method, based on your comment of "potentially there could be many" you would want to do a mapping (see other answers), and pass the json object to your server, where it can pass it to the next page.
With the same code -
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
alert('/next_page?ids=' + qs);
});
Here is a fiddle for you - http://jsfiddle.net/kellyjandrews/4dYfh/
I have a bunch of span4 class elements in my html. they look something like this:
<div class="span4">
<div class="widget">
<div class="header">blablabla</div>
</div>
</div>
I want to sort the span4 by that text iside header class.
I do this to sort them
$(".span4").sort(sortAlpha)
but how do I select the text inside the header class?
I'm doing this but I guess there is a better way
function sortAlphaAsc(a,b){
var nomeA = $(a.childNodes[1].childNodes[1]).text();
var nomeB = $(b.childNodes[1].childNodes[1]).text();
return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;
};
there must be a better way than
$(a.childNodes[1].childNodes[1]).text()
var elems = $(".span4");
elems.sort(function(a, b) {
return $(a).find('.header').text().toUpperCase().localeCompare(
$(b).find('.header').text().toUpperCase()
);
});
$(".span4").parent().html(elems);
FIDDLE
Try this:
function sortAlphaAsc(a,b){
var nomeA = $(a).find('div.header').text();
var nomeB = $(b).find('div.header').text();
return nomeA.toLowerCase() > nomeB.toLowerCase();
};
You could detach the spans, sort and append them.
That will be very fast too as changing elements in memory and only updating the DOM once in the end is very efficient.
var $spans = $(".span4").detach();
var sortedSpans = $spans.sort(function(spanA, spanB) {
var spanTextA = $("div.header", spanA).text();
var spanTextB = $("div.header", spanB).text();
return spanTextA > spanTextB;
});
$("body").append(sortedSpans);
Obviously instead of body you append it back to it's actual container element.
Or if the spans are in a common container store the parent in cache var $parent = $spans.parent() and in the end simply do $parent.html(sortedSpans).
I don't know your whole mark-up but that should get you started.
DEMO - Detach spans, sort them and append again
Do you mean something like this:
$('.span4').find('.header').text();
This will return the text inside the header div.
I want to select the id of the current div when I click on it in jQuery.
For example, say I have HTML like this:
<div class="item" id="10">hello world</div>
<div class="item_10">hello people</div>
When I click on the first div on .item class, I want to copy the id of the current div + adding to it the number (10), so it will be ("div id" + 10) equal to the second dev class = item_10.
I tried to use currentid = this.id; but it doesnt work :( !
First, note that id attributes starting with numbers are syntactically illegal in HTML4. If you're using id="10" make sure that you're using the HTML5 doctype (<!DOCTYPE html>).
It's hard to say why what you were doing didn't work without seeing your actual code. Presumably it is because you were registering for the event on a higher element (like the body) and this.id was the id of that higher element and not the element you clicked on.
In this case, you want to use the target property of the event to find what you clicked on. For example:
$(document.body).click(function(evt){
var clicked = evt.target;
var currentID = clicked.id || "No ID!";
$(clicked).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/
If you were registering on the specific elements instead, then this.id does work:
$('div').click(function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/1/
This is sub-ideal, however, because:
It makes many event handler registrations instead of 1, and
If additional divs are added to the document after this code is run, they will not be processed.
Under jQuery 1.7, you use the .on method to create a single event handler on a parent element with selectors for the kinds of elements you want to catch the event on, and have this set to them. In code:
$(document.body).on('click','div',function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/2/
I think you're trying to do something like:
$(".item").click(function(){
var id = $(this).attr("id");
var el = $(".item_" + id);
});
Now el is your second div.
You can simply use this.id
$('div').click(function() {
var divid = this.id;
alert($('.item_'+divid).html());
});
Demo
Something like this?:
$('div').click(function() {
theId = $(this).attr('id');
//Do whatever you want with theId.
});
This can be done as:
$('.item').click(function() {
var divId = $(this).attr("id");
});