How to get the ID of an element inside a div?

Asked

Viewed 2,696 times

0

I have a div and a few images, each image represents an item in a array global. When I drag this image to the div an edit form is enabled, otherwise a form is enabled to create new rule and generate a new image.

I need to know when there’s an image in div to enable include or edit mode and for this I need to know her ID as it is the index of array.

if(document.getElementById("manage").innerHTML == ""){
    console.log("vazio");
else{
    var id = document.getElementById("manage").innerHTML;
    console.log(id.attr("id"));
}

Like "id" is an string with the content:

img id="ico-3" class="img-drag" src="images/isp.jpg" draggable="true" ondragstart="drag(event)"

In this IMG example, the index in the array is 3.

  • Knowing the ID is the least of your problems, because the program can already recover the ID by the code you left here. The console.log(id.attr('id')) recovers the image ID and shows it on the console, so just take the ID value and format it the way you want, like a charAt().

  • then I expected something like this that I put in the log(attr), more generic and without going through the String but... Vlw by the help.

  • Can you post the structure of your HTML? This code you wrote shouldn’t work, because the innerHTML should return a string, and what would you call the attr in a string?!

  • Yes, your answer worked but you had to keep checking the id character amount. but the answer below fell like a glove. vlw

1 answer

4


Whereas you only have one image inside that div:

// Usando JavaScript puro
var img = document.querySelector("div.manage img.img-drag");
var id = null;
// Se a imagem existe na div
if(img) id = img.id;

// Usando jQuery
var id = $("div.manage img.img-drag").attr("id");

If the image exists id will be the id string, otherwise it will be null (first example) or undefined(jQuery).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.