简体   繁体   中英

Javascript inside HTML tags

I want to reference a Javascript variable inside an HTML tag like this:

<ul data-target="#{this.state.name}"></ul>

but it doesn't seem like this is valid syntax. I know that this is possible in Coffeescript, but is there a similar syntax in Javascript? I'm using ES6.

I believe it is not possible without some framework, eg. Angular.

On the other hand you can set the attribute of the element using plain javascript:

document.getElementById("my-thingy").setAttribute("data-target", "someStateName");

You seem to be looking for template literals that allow you to do string interpolation in ES6. The equivalent to Coffeescript 's

"<ul data-target=\"#{this.state.name}\"></ul>"

would be

`<ul data-target="${this.state.name}"></ul>`

You should remove the quotes. and concat the # with the state.name value.

<ul data-target={"#" + this.state.name}></ul>

As the doc says

The HTMLElement.dataset property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

Refer: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

Fetch the entire dataset object using the dataset property on the DOM element.

var eleDOM = document.getElementById('list');

eleDOM.dataset ;

fetch the individual property

eleDOM.dataset.data1;

Modify the individual data properties

eleDOM.dataset.data1 = "modified";

  //Fetch the entire dataset object using the dataset property on the DOM element. var eleDOM = document.getElementById('list') console.log(eleDOM.dataset); //fetch the individual property console.log(eleDOM.dataset.data1); //Modify the individual data properties eleDOM.dataset.data1 = "modified"; 
  <ul id ='list' data-data1 = "Panner" data-data2="Cheese"> </ul> 

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