JQuery: How do I get a DID ID? - javascript

I have the following HTML:
<div class="house">...</div>
But in my code I dynamically insert in DIV ID's to make the code then look like this:
<div class="house" id="id_1">...</div>
Question: How can I get the DIV ID by only knowing the CLASS using JQuery? I've tried something like the following but it doesn't work.
$('.house').getID();

$('div.house')
.each(function(index) {
alert( 'id for this div.class #'+index+': '+$(this).attr('id') );
});

Use the jQuery.attr() method to get and set attributes.
var houseId = $('.house').attr('id');
Note: This will only get the last '.house' element in the DOM's id.

I believe that
$('.house').attr("id");
Should work. I didn't test it though.

Related

jQuery .append() multiple #id's with one line?

I'm using the jQuery .append() function to input content into HTML elements via their id like so;
function returnGameDetailed(data) {
$('#game-synopsis').append(data.results.deck);
}
For some of the data.results I need to append them to multiple elements, is there a correct method to do this?
In the documentation I can only see a method for multiple inputs to the same element, not reversed.
Here's what i've attempted;
$('#game-title').$('#purchase-amazon').append(data.results.name);
and
$('#game-title', '#purchase-amazon').append(data.results.name);
You were almost right. The correct way is here:
$('#game-title, #purchase-amazon').append(data.results.name);
However, I'd recommend you to use classes instead:
$('.elements-to-insert').append(data.results.name);
<div class="elements-to-insert" id="game-title"></div>
<div class="elements-to-insert" id="purchase-amazon"></div>
Give both elements a class and then append to that class
$('.className').append(data.results.name);
The elements having the className will get appended with the html

Put an id to a parent element

I wanted to put an id in my element's parent element. Below is my code:
<div>
<div id="child"></div>
<div>
Im aware that jquery has a way to select a parent element , but I dont know how what method shall I use to put an id to it. Below is my jquery code:
div_resizable = $( "#child" ).parent();
div_resizable.id = "div_resizable";
Above code doesnt work with me. It doesnt throw an error, but no changes had taken effect. Any solution to my problem?
For achieve what you want, you can use the jquery attr:
$("#child" ).parent().attr('id', 'newID');
Or you can use the prop:
$("#child" ).parent().prop('id', 'newID');
And you can check the difference between the two here: difference between prop() and attr()
Of course div_resizable.id = "div_resizable" doesn't work. div_resizeable is an jQuery array and you are trying to assign id to it.
Try .attr instead:
$("#child").parent().attr({id: "div_resizable"});
To set a property on the first element inside a jQuery result object:
div_resizable = $( "#child" ).parent()[0];
// ^^^
div_resizable.id = "div_resizable";
This picks the first Element from the result so that you can directly access the property.
Or:
$('#child').parent().prop('id', 'div_resizable');
Use the .prop() helper method to accomplish the same thing.

Select a div insinde another div with jQuery

So I try to select a div within another div. My html goes like this:
<div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div>
I want to select my #cube0 within my Stage_game_page specifically, with jQuery or JS.
The goal of the selection is to use it in an loop.
I tried :
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#Stage_game_page")$("#cube"+i)[...]
}
I don't understand what I'm doing wrong.
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#cube"+i);
}
This is sufficient to select the "#cube0"/"#cube1"/"#cube2" etc. especially since ids are always unique. To answer the question $("#cube0", "#Stage_game_page")... that is how you select a div in another div
The id attribute should only be used once! I see above that you're using id="cube0" twice. If you want your divs to be recognized in multiple instances, use a class instead (the . instead of the #). Using the same id twice will probably break your script.
I believe for your html, you could use id "cube0", "cube1", etc., as long as you're ok with entering them manually. That should work for the loop you'd like to use.
Loops through each div that starts with the id cube inside Stage_game_page1
$("#Stage_game_page1 > div[id^='cube']").each(function () {
alert($(this).html());
});
JSFiddle
Child Selctor
Starts with Selector
use each() for loop.
$('#Stage_game_page1').children().each(function(index) {
// your code here with index starts from 0
});
or this using jquery attribute starts with selector
$('#Stage_game_page1').find('[id^="cube"]').each(function(index) {
// your code here
});
You need to use .find() or .children() or the like.
The correct jQuery usage would be
$("#Stage_game_page").find('#cube'+i)
to find a div with that id inside the container #stage_game_page
You have duplicate cube0 in your html code..
and i think the look should contain something like that:
$("#cube"+i)[...]
One another solution is:
$("#Stage_game_page1 div[id='cube0']")

Use a jQuery Selector as a Variable

I am creating a variable that stores an elements ID in the variable. I could write it like this:
var webappData = document.getElementById('web-app-data');
If I wanted to do the same using jQuery I think I would write it like this:
var webappData = $('#web-app-data');
However, when I try that it doesn't work. (Script throws an error because the variable isn't selecting the div with that Id.)
How would I use jQuery to select an element and store it in a variable?
document.getElementById('web-app-data') isn't the same as $('#web-app-data'). The later returns jQuery object, which is kind of an array of HTMLElement objects (only one in your case).
If you want to get HTMLElement, use $('#web-app-data')[0]. Check:
document.getElementById('web-app-data') === $('#web-app-data')[0]; // true
It's ok.. Maybe something else is wrong in your code..
Example:
<div id="web-app-data">
Hello
</div>
<script type='text/javascript'>
var webappData = $('#web-app-data');
alert(webappData.text()); // Hello
</script>
Fiddle
Above code should work just fine. Your problem might be, that jQuery doesn't find any corresponding elements from the DOM since the element has been removed or hasn't been loaded there yet. If you try to
console.log($('#web-app-data'));
that variable, you can check if jQuery actually found anything. jQuery object should have lenght of (atleast) one if corrensponding element is indeed in DOM atm.
That will work and you use just like it was the full JQuery selector.
var elm = $('#webappData');
if (elm.hasClass('someClass')) elm.removeClass('someClass');
return;

Finding a div with certain link inside

If I'm given a class of a div $('.my_class') and that a div contains a link a with a certain url which I'm also given, how do I find this div?
Here's how to do it:
$('div.my_class a[href="LINK"]').closest('div.my_class');
First find the link that is a child of your .my_class, then find the closest parent with that class. That will return you the original div:
$('.my_class a[href="mylink.com"]').closest('.my_class');
It sounds like your markup looks like this:
<div class="my_class">
Click me
</div>
So in jQuery it would look like:
$(".my_class").find("a[href='some_link']").closest(".my_class");
Try this
var certain_url = 'http://www.stackoverflow.com';
//...
var the_link = $('div.my_class a[href="'+certain_url+'"]').closest('div.my_class')
Like this.
$('div.my_class a[href="mylink"]').parent();

Categories

Resources