2

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.

1

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

2 Comments

I haven't seen this before - aren't you making a 'custom attribute' called data-stylecode ?
@Plato, it's HTML 5, you define custom attributes using the "data" attribute. The exact format is data-#, where # is replaced with the desired custom attribute name, then set to the desired string value.
2

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.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.