简体   繁体   中英

Copy string from DOM

I have a rookie problem.

I have div and I wanna copy the url from data-element= to .json file

How can i reach this?

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

You can use 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. To access any attribute of element use getAttribute('attribute_name') function HTML

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

JS

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

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