Yes, you can set any aspect of an element based on any aspect of any other element. You do need to choose a point in time when that should happen (on page load, on the click of another element, etc.).
Here's an example that sets up an <a>
element with an href
that matches the data-schemaid
attribute value of the div
upon page load and appends that a
element into the document (by the way, you do understand that the value of the div
you have shown isn't a valid URL by itself and would need to be adjusted to be valid to navigate to, right? If you just want the clicking of the <a>
to navigate (scroll) to the <div>
, you'd just need to prepend a "#" to it, as shown below.):
// Set up an event handler for when the document is parsed and ready to be interacted with:
window.addEventListener("DOMContentLoaded", function(){
// Scan the document for the dynamically generated div that has a `data-schemaid` attribute
var theDiv = document.querySelector("div[data-schemaid]");
var newA = document.createElement("a"); // Create a new <a> element
newA.href = "#" + theDiv.dataset.schemaid; // Set the href to the div's attribute value
newA.textContent = "Click Me"; // Give the new <a> some text to click on
document.body.appendChild(newA); // Append the new <a> to the end of the body
});
<div data-schemaid="my-id-name">
</div>
Or, if the <a>
element already exists in the document (and doesn't need to be appended), then the solution is a bit simpler:
// Set up an event handler for when the document is parsed and ready to be interacted with:
window.addEventListener("DOMContentLoaded", function(){
// Scan the document for the dynamically generated div that has a `data-schemaid` attribute
var theDiv = document.querySelector("div[data-schemaid]");
var speicalA = document.getElementById("specialA"); // Get a reference to the <a> element
speicalA.href = "#" + theDiv.dataset.schemaid; // Set the href to the div's attribute value
});
<div data-schemaid="my-id-name">
</div>
<a id="specialA">Click Me</a>