user1283776
user1283776

Reputation: 21764

Event.target.name works for input but not div?

The onBlur handleBlur function outputs the value from the name attribute for the input tag, but undefined for the div tag. Why does it not output the value from the name attribute for the div tag as well?

import React, { Component } from "react";

export default class Editable extends Component {
  constructor(props) {
    super(props);
  }

  handleBlur(event) {
    console.log(event.target, event.target.name);
  }

  render() {
    return (
      <div>
        <div
          name={this.props.name}
          contentEditable={true}
          onBlur={this.handleBlur}
          dangerouslySetInnerHTML={{ __html: this.props.html }}
        />
        <input name={this.props.name} onBlur={this.handleBlur} />
      </div>
    );
  }
}

Upvotes: 3

Views: 1901

Answers (1)

acdcjunior
acdcjunior

Reputation: 135752

<div>s don't have a name property. You can have an attribute, but a property is something else (more down below).

Also, because the value of this.props.name is empty, React is not rendering the attribute, which makes you get null even if you try to get the attribute. So try do add some value to the attribute and log event.target.getAttribute('name') as below:

 handleBlur(event) {
    console.log(event.target, event.target.name);
    console.log(event.target, event.target.getAttribute('name'));       // added this
  }

  render() {
    return (
      <div>
        <div
          name={this.props.name + "SOMETHING"}                         // added this
          contentEditable={true}
          onBlur={this.handleBlur}
          dangerouslySetInnerHTML={{ __html: this.props.html }}
        />
        <input name={this.props.name} onBlur={this.handleBlur} />
      </div>
    );
  }

The above would output:

<div name=​"undefinedSOMETHING" contenteditable=​"true">​</div>​ undefined
<div name=​"undefinedSOMETHING" contenteditable=​"true">​</div>​ "undefinedSOMETHING"



More about the div and name property:

console.log(document.getElementById("d").name)
console.log(document.getElementById("i").name)
console.log('---');
console.log(document.getElementById("d").getAttribute('name'))
console.log(document.getElementById("i").getAttribute('name'))
<div id="d" name="alice"></div>
<input id="i" name="bob">

Docs:

Upvotes: 4

Related Questions