score:0

Now you can use the useRef hook to easily reference an element:

function MyComponent() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // @ts-ignore (us this comment if typescript raises an error)
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus on input</button>
    </>
  );
}

score:1

You can try with currentTarget

 let a = e.currentTarget.parentNode.getAttribute("key");

Or

 let a = ReactDOM.findDOMNode(this).parentNode.getAttribute("key")

score:2

you can change 'key' attribute to 'data-key' and get attribute like this:

// Example class component
class Test extends React.Component {
constructor(props){
super(props);
this.deletepost = this.deletepost.bind(this);
}
deletepost(e) {
let a = e.currentTarget.parentNode.getAttribute("data-key");  
  console.log(a);
}

render() {
        return (
          <div>
          { this.props.posts.map((post, i) =>
            <div id="a" data-key={post.key}>
            <span> <h3>{post.title}</h3><p>{post.post}</p></span>
            <input type="button" value="Delete" id={i} onClick={this.deletepost}/>
            </div>
          ) 
        }        
        </div>
        )
    }    
}

// Render it
ReactDOM.render(
  <Test posts={[{post:'a',key:1},{post:'b',key:2}]} />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

score:3

In ReactJS, the "key" is for React's internal use and won't be included in the DOM. That may be the reason you are getting null.

You need to simply add another prop/attribute. Something like below should work.

deletepost(e) {
let a = e.target.parentNode.getAttribute("postid"));
  console.log(a);
}

render() {
    return (
      <div>
          {     
          this.props.posts.map((post, i) =>
            <div id="a" key="1" postId="1">
            <span> <h3>{post.title}</h3><p>{post.post}</p></span>
            <input type="button" value="Delete" id="1" onClick={this.deletepost}/>
            </div>
          ) 
        }        
     </div>
        )
    }    
}

Also, if the "id" on the input element is same as the "key" on your div (parent) element, then you can simply do the following:

deletepost(e) {
let a = e.target.id;
  console.log(a);
}

render() {
    return (
      <div>
          {     
          this.props.posts.map((post, i) =>
            <div id="a" key="1">
            <span> <h3>{post.title}</h3><p>{post.post}</p></span>
            <input type="button" value="Delete" id="1" onClick={this.deletepost}/>
            </div>
          ) 
        }        
     </div>
        )
    }    
}

Related Query

More Query from same tag