-1

I have a pretty simple query here. I have a view page with an div and a form element. This is how they look.

<div id="candy" value="valueOfCandy" ></div>

<input type="text" value="javascript:document.getElementById('candy').getAttribute('value')"/>

I need to access the value of candy inside input's attribute (it can be any attribute).

I tried the code as I have shown above but that didnt work. I researched on StackOverflow too but couldnt find anything satisfactory. Please help out.

Edit: Thank you everyone. I found the answer to that, which I am gonna mark. Also, deleting this question so that it doesnt confuse someone else.

  • 1
    That won't work. What are you trying to do? – Ason Mar 14 '18 at 12:48
  • 1
    I will save you much pain an misery. Never put JavaScript in HTML, outside of a script tag. Ever. – Jared Smith Mar 14 '18 at 12:48
  • 3
    Why do you need to do this inside the element? Why not set the value outside of the element? – adprocas Mar 14 '18 at 12:48
  • 2
    And no need for `javascript:` label ever – mplungjan Mar 14 '18 at 12:50
  • Perhaps you mean `` – mplungjan Mar 14 '18 at 12:51
  • 1
    *"I need to access the value of candy inside input's attribute (it can be any attribute)."* **When** do you need to do that? Why do you think you need to do it in the markup? What about when the user changes the value? I think you have an [X/Y problem here](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Also note that `value` is not a valid attribute for `div` elements; if you need to embed your own data in attributes, use a [`data-*` attribute](https://html.spec.whatwg.org/#embedding-custom-non-visible-data-with-the-data-*-attributes). – T.J. Crowder Mar 14 '18 at 12:53
  • `I tried the code` Unfortunately you tried no code, there is no code here. – Keith Mar 14 '18 at 12:54

5 Answers5

4

If I assume you want to do this at page load, do it like this

Note 1, custom attributes should have a data- prefix and use .dataset to access its value.

Note 2, for older browsers like IE10 and below, you need getAttribute (as in 2nd sample below).

Stack snippet 1

<div id="candy" data-value="valueOfCandy"></div>

<input id="candy2" type="text" value="" />

<script>
  document.getElementById('candy2').value =
  document.getElementById('candy').dataset.value
</script>

Stack snippet 2

<div id="candy" data-value="valueOfCandy"></div>

<input id="candy2" type="text" value="" />

<script>
  document.getElementById('candy2').value =
  document.getElementById('candy').getAttribute('data-value')
</script>
Ason
  • 79,264
  • 11
  • 79
  • 127
  • `div` elements don't have a `value` attribute. – Scott Marcus Mar 14 '18 at 12:59
  • @ScottMarcus Correct, and where did I used that? – Ason Mar 14 '18 at 12:59
  • In your `div` tag? – Scott Marcus Mar 14 '18 at 13:00
  • @ScottMarcus No, take a look again...`candy2` is an `input`, the `div` use `getAttribute` – Ason Mar 14 '18 at 13:02
  • It doen't matter how you are extracting the data. `value` is invalid on a `div`. The HTML is invalid. `getAttrbute()` doesn't care about validity. – Scott Marcus Mar 14 '18 at 13:03
  • Yes, although it might work. custom attributes should start with `data-`. – Keith Mar 14 '18 at 13:03
  • @ScottMarcus You are correct, I've updated my answer – Ason Mar 14 '18 at 13:04
  • And, now that your HTML is valid, you should be using `.dataset` to extract a `data-*` attribute (even though `.getAttribute()` works). – Scott Marcus Mar 14 '18 at 13:04
  • @ScottMarcus Thanks...keeps me on my toes :) ... answer updated – Ason Mar 14 '18 at 13:08
  • @ScottMarcus That's interesting, getAttribute is of course more compatible with older browsers,.. Is there any link to why `.dataset` should be used instead?. – Keith Mar 14 '18 at 13:09
  • @Keith https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset – Ason Mar 14 '18 at 13:10
  • @Keith See my answer for the links to the documentation. But, `.dataset` has been standard for several years now (part of HTML5). It's not new. – Scott Marcus Mar 14 '18 at 13:11
  • No, it was not. – Scott Marcus Mar 14 '18 at 13:12
  • @ScottMarcus I understand all that, but I'm struggling to see where using `getAttribute` should be avoided. From the link @LGSon posted, it's just a nice wrapper for accessing `data-` attributes. If it's just for nicer coding, I can understand that. But just worried it was a depreciated option to use `getAttribute` etc. – Keith Mar 14 '18 at 13:14
  • 1
    Datasets are not compatible with IE10 - getAttribute is compatible with all browsers currently worth supporting – mplungjan Mar 14 '18 at 13:16
  • @Keith It's not deprecated as `.getAttribute()` is a standard DOM API and is needed for a variety of other attribute access. It's simply the correlating API to `data-*`. As I said, `getAttribute()` works. – Scott Marcus Mar 14 '18 at 13:16
  • @mplungjan Thanks...added a note about that – Ason Mar 14 '18 at 13:18
  • 1
    @ScottMarcus `you should be using` yeah, it was maybe just the wording that got me worried. Maybe `you could use`, would have not frightened me so much.. :) – Keith Mar 14 '18 at 13:20
2

Do it in JavaScript outside of code but after the objects exist.

Here's an example of how to achieve this:

var candy = document.getElementById('candy').getAttribute('data-value');

document.getElementById('input').value = candy;
<div id="candy" data-value="valueOfCandy" ></div>
    
<input id="input" type="text"/>

As mentioned in the comments, please make sure your JavaScript code is loaded after your markup. There are various ways to do this, including waiting for the dom to load.

See $(document).ready equivalent without jQuery and How does the location of a script tag in a page affect a JavaScript function that is defined in it? for more information.

adprocas
  • 1,827
  • 1
  • 13
  • 28
  • 1
    What do you mean what event? There is no mention of an event in the post. – adprocas Mar 14 '18 at 12:53
  • @mplungjan: That's a flaw in Stack Snippets (which I reported years ago, but SE didn't care), not in the answer. When you run the snippet, it has them in the correct order. – T.J. Crowder Mar 14 '18 at 12:54
  • @mplungjan, the snippet works. This isn't a question about where to put the JavaScript code. The order is how the snippet system on stackoverflow adds the different sections. – adprocas Mar 14 '18 at 12:54
  • @mplungjan stack snippets place ` – Patrick Roberts Mar 14 '18 at 12:54
  • 1
    Trying to explain execution of scripts against HTML might be more useful outside a stack snippet – Sven Writes Code Mar 14 '18 at 12:55
1

Try this

document.getElementById('input').value =  document.getElementById('candy').dataset.value
<div id="candy" data-value="valueOfCandy" ></div>
<input id="input" type="text" value=""/>
Mustafa Çetin
  • 271
  • 2
  • 10
0

This is not how you should be doing this.

JavaScript should be separated out of the HTML completely to avoid a whole host of issues. Including JavaScript in the HTML as you are attempting is a 20+ year old technique that was used before we had standards.

Next, a div element can't have a value attribute. value is only for form fields. But, you can create a data-* attribute, which allows for you to create custom attributes. You can then extract that value using the .dataset property.

See below:

// This code would be placed inside of <script> and </script> tags and the whole 
// thing would be placed just before the closing body tag (</body>).
document.getElementById("result").value = document.getElementById('candy').dataset.value;
<div id="candy" data-value="valueOfCandy"></div>

<input type="text" id="result">
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
0

Put that code either within a script tag or in a separated js file.

Further, always bind the event DOMContentLoaded when you need to manipulate DOM elements.

DOMContentLoaded

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

This way, your logic is totally consistent.

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");

  document.getElementById('candy2').value =
    document.getElementById('candy').getAttribute('value')
});
<div id="candy" value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />

A recommendation is to use data-attributes because the value attribute is related to form fields:

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");

  document.getElementById('candy2').value =
    document.getElementById('candy').dataset.value;
});
<div id="candy" data-value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
Ele
  • 31,191
  • 6
  • 31
  • 67
  • 1
    *always bind the event DOMContentLoaded when you need to manipulate DOM elements* Actually, if you just place the code at the end of the `body`, you get the correct timings, with less code and less memory usage, so *always* isn't really recommended. – Scott Marcus Mar 14 '18 at 13:08
  • @ScottMarcus the usage of `DOMContentLoaded` is totally recommended to avoid any problem is future changes in the HTML's structure. It's a **must-have** because just putting that code (javascript) at the bottom of body is not enough. – Ele Mar 14 '18 at 13:20