简体   繁体   English

从 DOM 复制字符串

[英]Copy string from DOM

I have a rookie problem.我有一个菜鸟问题。

I have div and I wanna copy the url from data-element= to .json file我有 div,我想将 url 从 data-element= 复制到 .json 文件

How can i reach this?我怎样才能达到这个目标?

<div content="" id="preview" data-element="http://thereislink" 
class="sampleclass"></div>

You can use getAttribute您可以使用getAttribute

 let x = document.getElementById('preview').getAttribute('data-element'); console.log(x)
 <div content="" id="preview" data-element="http://thereislink" class="sampleclass">Test</div>

Or directly use dataset或者直接使用数据集

 let x = document.getElementById('preview').dataset.element; console.log(x)
 <div content="" id="preview" data-element="http://thereislink" class="sampleclass">Test</div>

To select an element you can use different JavaScript Selectors .In this Example I am selecting element by Id.要选择一个元素,您可以使用不同的JavaScript 选择器。在此示例中,我按 Id 选择元素。 To access any attribute of element use getAttribute('attribute_name') function HTML要访问元素的任何属性,请使用getAttribute('attribute_name')函数HTML

<div content="" id="preview" data-element="http://thereislink" 
class="sampleclass"></div>

JS JS

var url= document.getElementById("preview").getAttribute("data-element");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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