Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to getElementByID in a specific DIV block (JS or JQUery)

I just wanted a fast/easy/simple way to check for existing ID on a specific element (div in this case)..

Can't seem to find code sample for this..im using jquery but i dont think i need to do jquery on this one, just basic getElement.. but i need to isolate the search inside a div block.. because the id does exist in other elements on the page but i need to know if it exist in a specific area/div.

so instead of just

document.getElementById(target_id);

i need something like:

divName.getElementById(target_id);

or

$("document.divName").getElementById(target_id);

or

$(".divName").document.getElementById(target_id);

Can't seem to find something that works.

like image 437
BrownChiLD Avatar asked Nov 27 '22 17:11

BrownChiLD


2 Answers

IDs are supposed to be unique and no two elements in page should have same id. You may search some element with some class in div with specific ID.

$('#divId .someClass')

or using find()

$('#divId').find('.someClass')

or using context, jQuery( selector [, context ] )

$('.someClass', $('#divId'))
like image 70
Adil Avatar answered Dec 05 '22 02:12

Adil


    var mySubDiv = myParentDiv.querySelector("#mySubDivId")

is equivalent to

    var mySubDiv = document.querySelector("#myParentDivId #mySubDivId"); 
    // don't forget the space :  #myParentDiv#mySubDivId won't work

where querySelector and querySelectorAll are very useful functions, enough for me to avoid using jQuery : they accept any css selector

in real life, using the same Id for different DOM elements often happens.

like image 39
reuns Avatar answered Dec 05 '22 01:12

reuns