JScript - Discovering the id of the previous div

1

Good afternoon! Home I need a help to get the value of the previous div (red DIV01 )
What command can I use to get the result ?? Home The above Div is the right parent element? Home Sorry for 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>
    
asked by anonymous 05.10.2017 / 19:57

2 answers

2

You have several ways, you can go by:

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

  • using recent technology .closest() (not supported in IE together 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 .closest() which I think is the best option, you can add this to make it compatible with older 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;
    };
}
    
05.10.2017 / 20:00
1

Just get the id attribute 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>
    
05.10.2017 / 20:01