How to catch a Parent element from a child with id?

Asked

Viewed 562 times

1

I have the following code:

<div></div>

<div>
  <div class='minhaClasse'>
    <div id='text'>hhaushdus</div>
    <input name='profile_id' />
  <div>
</div>

I need to take this div:

<div class='minhaClasse'>
  <div id='text'>hhaushdus</div>
  <input name='profile_id' />
<div>

I tried this way:

let element = document.getElementsByName('profile_id')[0].parentNode;

that returned me the father:

<div>
  <div class='minhaClasse'>
    <div id='text'>hhaushdus</div>
    <input name='profile_id' />
  <div>
</div>

Basically it’s two questions, how do I get this div with class 'madcap' and you can make a getElement of a getElement guy:

document.getElementsByName('profile_id')[0].parentNode.getElementByClassName('minhaClasse'));
  • But the goal is to catch a parent element with the class minhaClasse or a brother ? In the given example minhaClasse is the father of profile_id

2 answers

1

you can do the following:

x = document.getElementsByClassName("minhaClasse");

this will return all the elements that have this class, then you just iterate and perform the process you want:

for (var i = 0; i < x.length; i++) {
    //seu código aqui
}

0

I recommend taking a look at https://www.w3schools.com/jsref/prop_node_childnodes.asp I can’t remember which syntax is right but I think this particular code might help you https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_node_childnodes2

EDIT

I forgot to put some details to reference a specific div you must show the code which div vc want, recommend putting an id in the parent div and dps execute the commands and codes you want,

Example:

function myFunction() {
    var c = document.getElementById("myDIV").childNodes;
    c[1].style.backgroundColor = "yellow";
}
<div></div>

<div id="myDIV">PAI
  <div class='minhaClasse'>FILHO
    <div id='text'>hhaushdus</div>
    <input name='profile_id' />
  <div>
</div>

<button onclick="myFunction()">Try it</button>

  • I just wanted to understand why they’re negative if I’m trying to help ... and if the answer isn’t wrong by itself

  • I recommend not putting the article link, instead, transfer it.

  • 1

    I edited giving an example... But now I will actually write and put fonts

Browser other questions tagged

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