Jscript - Finding the id of the previous div

Asked

Viewed 100 times

1

Good afternoon !
I need some help to get the value of the previous div (red DIV01)
What command can I use to get the result??
The previous Div is the right parent element?
Excuse the ignorance.

function onClick(){}
#DIV1{
	width:300px;
	height:300px;
	background-color:red;
}

#DIV2{
	width:200px;
	height:200px;
	background-color:blue;
}
<div id="DIV1"> 
	<div id="DIV2">
		<button onclick="onClick()"> teste </button>
	</div>
</div>

  • 1

    What value you need?

  • Of the ID of DIV01, who can get the ID of the previous div

2 answers

2


You have many ways,
you can go through:

  • .parentElement.parentElement (works but will break if you change the structure of the DOM)

  • using recent technology .closest() (not supported in IE) together with MDN polyll below.

Example:

function onClick(btn) {
  var maneiraA = btn.closest('#DIV1');
  var maneiraB = btn.parentElement.parentElement;

  console.log(maneiraA.id);
  console.log(maneiraB.id);
}
#DIV1 {
  width: 300px;
  height: 300px;
  background-color: red;
}

#DIV2 {
  width: 200px;
  height: 200px;
  background-color: blue;
}
<div id="DIV1">
  <div id="DIV2">
    <button onclick="onClick(this)"> teste </button>
  </div>
</div>


If you use the .closest() which I think is the best option, you can add this to make it compatible with old browsers:

if (window.Element && !Element.prototype.closest) {
    Element.prototype.closest = 
    function(s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
            i,
            el = this;
        do {
            i = matches.length;
            while (--i >= 0 && matches.item(i) !== el) {};
        } while ((i < 0) && (el = el.parentElement)); 
        return el;
    };
}
  • The . parentElement it goes backwards from div to div and the Closest goes directly to what I need? It’s about that??

  • Thanks again @Sergio !! was a big help

  • 1

    @Exact sora. I prefer the .closest() but use what suits you best. Note that I spent the this in the HTML for the function to receive the clicked element.

1

Just take the attribute id of parentNode of DIV2:

//função executada no clique
function onClick(){
  //pega a div2
  var div2 = document.getElementById('DIV2');
  //pega o pai da div2
  var div1 = div2.parentNode;
  //escreve o id do pai da div 2
  console.log(div1.id);
}
<div id="DIV1"> 
	<div id="DIV2">
		<button onclick="onClick()"> teste </button>
	</div>
</div>

  • Ah, I got it !!! thanks for the explanation Arthur

Browser other questions tagged

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