简体   繁体   中英

Get custom field value on span element using javascript

If I have something like this:

<span stylecode="123456789" class="punctis-social-widget"></span>

How can i get the stylecode value using javascript (not jquery). Also, is valid to use custom fields on spans?

Note: The field stylecode sometimes is not present, so the result of the function could be null.

It's not valid to use custom attributes. If you need to store any values consider using the HTML5 data attribute.

<span id="item1" data-stylecode="123456789" class="punctis-social-widget"></span>

Then use JS to fetch that:

<script>
    var element = document.getElementById('item1');  // You could use class
    var sDataValue = element.getAttribute('data-stylecode');  //123456789
</script>

For jQuery fetch value with:

$('item1').data('stylecode');  //123456789

Provided you can select the span element, you can simply do this:

spanElem.getAttribute('stylecode');

If the attribute doesn't exists, getAttribute() will simply either return null or a '' (seems to vary between browsers).

Selecting it would be easier if it had an id, in which case you could use document.getElementById('id'); Otherwise you can use document.getElementsByClassName('punctis-social-widget') in newer standards-compliant browsers, or use document.getElementsByTagName('span'); and loop over them and inspect their className properties.

As mentioned by Matthew, custom attributes are not valid (but usually don't cause any problems afaik), but provided you use HTML 5, turning it into a data-attribute will make it valid.

Though it is not good practice to use custom attributes like this, you can accomplish this task as such:

var apan = document.getElementsByTagName('span');
var code = span[0].getAttribute('stylecode');
console.log(code);

Use the data attributes.

I know how to catch the value of attribute :

var span = document.getElementsByTagName("span");
var stylecode = span.getAttribute("stylecode");

But I don't know about the second part of your question. Sorry.

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