Mukund
Mukund

Reputation: 1105

how to get the div id of a specific level of DOM?

consider my html page be like this

<html>
 <body>
   <div id = "mainDiv">
     <div id = "levelOne1">
        <div id="levelTwo1">
          <div id = "levelThree1">
              third level html content over here
          </div>
        </div>
        <div id="levelTwo2">
               second level html content over here
        </div>
     </div>
      <div id = "levelOne2">
             second level html content over here in levelOne2      
     </div>
      <div id = "levelOne3">
                <div id="innerdiv">
             second level html content over here in levelOne3   
                 </div>
     </div>
   </div>
 </body>
</html>

and this function in js returns the id of the respective parent from where you have selected the text from

function getSelectionParentElement() {
  var parent = null,
  selection;
  if (window.getSelection) {
    selection = window.getSelection();
    if (selection.rangeCount) {
      parent = selection.getRangeAt(0).commonAncestorContainer;
      if (parent.nodeType !== 1) {
          parent = parent.parentNode;
      }
    }
  } else if ((selection = document.selection) && selection.type !== "Control") {
    parent = selection.createRange().parentElement();
  }
  return parent;
}

and if i call this code after selecting some text from this third level html content over here from html page and on any click function i wrote the code as

var divElement = getSelectionParentElement();

var divID = divElement.getattribute('id');

where divID is obtained as levelThree1.

but what i want is the id of corresponding level two div that is levelOne1

let me be clear i always want the id the of the respective second level div

so if i select something from this text

second level html content over here

i still want id as levelOne1

and if i select sonething from this text

second level html content over here in levelOne2

the div id should be levelOne2

and if is select this text

second level html content over here in levelOne3 the div id should be levelOne3

is there any way of accomplishing it?

can we generalize it? like second level, third level etc?

Upvotes: 0

Views: 473

Answers (4)

Mukund
Mukund

Reputation: 1105

Thanks to @Mukesh Patil, i accomplished the same

function getSecondLevelElement(elem) {
                var immediateId = new Array();
                var i =0;
                    while (elem = elem.parentNode) { 
                        if(elem.getAttribute('id')==="mainDiv")
                        {
                      console.log(elem.getAttribute('id')+"  <> "+i); 

                      break;
                        }
                        immediateId[i] = elem.getAttribute('id');
                      i=i+1;
                    }
                    return immediateId[i-1];
                }

Upvotes: 0

Mukesh Patil
Mukesh Patil

Reputation: 146

You can achieve this by adding a particular class to the second level elements. For example, add class 'second-level-element' to all the second level elements. In your case you can add class 'second-level-element' to divs with Ids levelOne1, levelOne2, levelThree.

Then do this to check that the selected element is descendent of which second level element:

considering 'elem' is selected element,

function getSecondLevelElement(elem) {
    while (elem = elem.parentNode) { 
        if (elem.className == "second-level-element") {
            return id = elem.id;
        }
    }
}

And then call this function by passing the element whose text is selected as the parameter.

Upvotes: 1

Farid Murzone
Farid Murzone

Reputation: 136

If i understood well you can use child nodes.

var divElement = getSelectionParentElement();
var secondDiv = divElement.getElementsByTagName('div')[1];
var divID = secondDiv.getattribute('id');

I separated the secondDiv in a new variable to be clear. But you can write all in one line. Also you can use '.children[1]' instead of '.getElementsByTagName('div')[1]', the difference is that children[1] will get the second child in the divElement no matter if it is a div or p or another kind of element.

Another choice may be use ":nth-child(n)" pseudoclass with jQuery.

Upvotes: 1

Itay Gal
Itay Gal

Reputation: 10824

Just use generic function:

function getIdByLevel(level){
  var element = $("#mainDiv");  // <- set the container in which you're searching
  for (var i = 0; i < level; i++){
    element = $(element).find("div")[0]; // <- the first div in each level is being taken
  }
  $("#res").html("id is: " + element.id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainDiv">
  <div id="levelOne1">
    <div id="levelTwo1">
      <div id="levelThree1">
        third level html content over here
      </div>
    </div>
    <div id="levelTwo2">
      second level html content over here
    </div>
  </div>
  <div id="levelOne2">
    second level html content over here in levelOne2
  </div>
  <div id="levelOne3">
    <div id="innerdiv">
      second level html content over here in levelOne3
    </div>
  </div>
</div>
<br/><br/>
<button onClick="getIdByLevel(1);">Get Level 1 Id</button>
<button onClick="getIdByLevel(2);">Get Level 2 Id</button>
<button onClick="getIdByLevel(3);">Get Level 3 Id</button>
<div id="res"></div>

Upvotes: 1

Related Questions