最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - Get custom field value on span element using javascript - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Mar 27, 2013 at 13:47 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Mar 27, 2013 at 13:31 DomingoSLDomingoSL 15.5k25 gold badges104 silver badges179 bronze badges 1
  • possible duplicate of How do I access custom html attributes in javascript? – Felix Kling Commented Mar 27, 2013 at 13:47
Add a ment  | 

4 Answers 4

Reset to default 4

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-pliant 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 acplish 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.

发布评论

评论列表(0)

  1. 暂无评论