Pregunta

How can I select the element of HTML and get its data attribute without using jquery?

For instance, I have this html tag with some data attribute,

<html xmlns="http://www.w3.org/1999/xhtml" class="no-js" data-directory='{"base_url":"http://localhost/mywebsite/","core_package":"base/","local_package":"base/"}'>

This is a jquery way,

var directories = $('html').data('directory');

What about javascript's native way?

Also, how can I select the script tag and get its attribute data?

For instance, I have this script tag,

> <script
> data-main="http://localhost/mywebsite/local/view/javascript/base/main"
> src="http://localhost/mywebsite/core/view/javascript/base/ext/require/require.js"></script>

a jquery way,

var base_url = $('script[src$="require.js"]').attr('src').split(/\b(?:core|local)\b/)[0];

But I need a javascript native way. Is it possible?

¿Fue útil?

Solución

Using getElementsByTagName

1. .getAttribute("data-directories")

var directories = document.getElementsByTagName("html")[0].getAttribute("data-directory");

2. .src or .getAttribute("src") works the same

var base_url=document.getElementsByTagName("script")[0].src.split(/\b(?:core|local)\b/)[0];

For newer browsers document.querySelector can be used like jQuery selectors which is of course smarter if there are more than one script on the page

var base_url=document.querySelector('script[src$="require.js"]').src.split(/\b(?:core|local)\b/)[0];

Otros consejos

Try

var base_url = document.querySelector('script[src$="require.js"]').getAttribute("src").split(/\b(?:core|local)\b/)[0];

Use .getAttribute

var selector=document.getElementsByTagName('html')[0];

//Using DOM's getAttribute() property
var dataAtributte=selector.getAttribute("data-directory");
//retuns  {"base_url":"http://localhost/mywebsite/","core_package":"base/","local_package":"base/"}

First of all, why you want to do it with native JavaScript when with jQuery is so much easier and you know how to do it ?

The analogue of $('html') selector is document.getElementsByTagname("html") which will return you an array of elements so you have to get the [0] index for the first html tag. Then for your attributes you should do something like .getAttribute("attr-name") in your case attr-name is data-directory. So finally you get a row like

document.getElementsByTagname("html")[0].getAttribute("data-directory");

For your second problem just do the same but chage the Tagname value and the getAttribute value.

document.getElementsByTagname("script")[0].getAttribute("data-main");

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top