Search code examples
javascripthtmlvar

Javascript grabbbing a html5 data- value to use as a var


So I want to customize the src via js with hidden data but just can't figure out the right flow to write it. Looking to grab html5 data- to change the src. Any time I have tried to write it can't get it to grab my data- with Var.

referencing question 19320436 for var from data when looking for answers

tried

<html>
<body>

<p id="test" class="customClass" data-newsrc="https://stackoverflow.com"></p>

<script>
var value = $('.customClass').data('newsrc');

document.getElementById("test").innerHTML= '<iframe id="myframe" src=""\>\</iframe>';

document.getElementById("myframe").src= value;
</script>
</body>
</html>

works but is not grabbing a new value from page

<html>
<body>

<p id="test" class="customClass" data-newsrc="https://stackoverflow.com"></p>

<script>

var value = "https://stackoverflow.com/qestions"

document.getElementById("test").innerHTML= '<iframe id="myframe" src=""></iframe>';

document.getElementById("myframe").src= value;
</script>
</body>

Solution

  • First select the #test element, you'll need it more than once. Without using jQuery you can select the data-newsrc property by accessing it from the dataset property.

    Instead of writing your HTML in a string, create a new element object with document.createElement, this saves you the step of having to reselect the iframe because you already have a reference.

    After setting the src, append the iframe to the test element.

    const test = document.getElementById('test');
    const src = test.dataset.newsrc;
    const iframe = document.createElement('iframe');
    iframe.src = src;
    test.append(iframe);
    <p id="test" class="customClass" data-newsrc="https://stackoverflow.com"></p>