Sobiaholic
Sobiaholic

Reputation: 2957

JavaScript substring from an element

This is some simple JavaScript code I would like to implement, butit does not work.

I'm trying to get the file link inside the tag file but I think innerHTML does not work in this kind of situation, but I've given it a shot to try.

Could you guys help me with this? I know I'm missing something here.

[videoplayer id="one" file="/dir1/dir2/hi.mp4" width="333" height="333" /]


<script type="text/javascript">
var str = document.getElementById('one').innerHTML;
document.write(str.substr(0,str.length-1));
</script>

Upvotes: 4

Views: 1206

Answers (2)

RightSaidFred
RightSaidFred

Reputation: 11327

Use getAttribute() to retrieve the value of the file attribute.

var str = document.getElementById('one').getAttribute('file');

alert( str );

Probably a good idea to also make sure the element was found:

var el = document.getElementById('one');

if( el ) {

    alert( 'Element was found!' );

    var str = el.getAttribute('file');

} else {

    alert( 'NO element was found' );

}

alert( str );

Upvotes: 4

Blender
Blender

Reputation: 298076

You use the getAttribute function:

var str = document.getElementById('one').getAttribute('file');

innerHTML only works if there is HTML code inside of the tags:

<foo>
  Hello!
</foo>

But that is not the case for you.

Upvotes: 2

Related Questions