简体   繁体   中英

javascript set focus on contenteditable area using data- attribute and value

I've got a template full of contenteditable areas that may or maynot already have id attributes. The one difference is that they all contain unique data- values so I'd like to use them to help me target/focus my cursor programically on specific areas for editing.

If I store the data- value in a var this way:

textArea[0] = this.getAttribute("data-id");

and my user looses focus on the contenteditable area they are currently work in, how can I force the cursor back to it?

document.[data-id=textArea[0]].focus();

Thank you for your time.

If you use vanilla js, you can write something like:

document.querySelectorAll('[data-id="' + dataId + '"]')[0].focus()

(check this answer on how to select elements by attribute)

If you can use Jquery you can just have:

$('[data-id="' + dataId + '"]').focus();

You can check also this fiddle in case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM