简体   繁体   中英

Javascript - extract span value

Hi there i was wondering how you would get the Span Value="Example" from an object using JavaScript.

playlist = document.getElementById("list");
playlist.addEventListener("click",playNext,false);  

function playNext(){

var next = playlist.value;

    alert(next); }

As for the html

<span id="list" value="neededValue">Object1</span>

I am unable to extract the "neededValue" from this span object, however i have had success returning the innerHTML from this span.

Thanks,

You probably want to use a data attribute to store the value. Here is a good article on what they are and how to use them http://html5doctor.com/html5-custom-data-attributes/

You need to use data-attributes, as a span don't has a value:

<span id="list" data-one="neededValue">Object1</span>

var a = document.getElementById('list');
alert (a.getAttribute('data-one'));

DEMO

If you already have to many span elements with value, you can do it like this, but I would consider this as not good practice:

var a = document.getElementById('list');
alert (a.getAttribute('value'));
<span id="list" data-value="neededValue">Object1</span>


var playlist = document.getElementById("list");
playlist.addEventListener("click", playNext, false);  

function playNext(){
  var next = playlist.getAttribute("data-value");
  alert(next);
}

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