简体   繁体   中英

Get HTML element attribute from javascript

I stuck again in beginner-spheres of JS. :/

I want to get the number from data-channel-id , which is found by the call in variable spans :

<main class="soft--top" data-channel-id="348" data-preview-mode="">

This is my JS:

window.onload = function (){
var spans = document.getElementsByTagName('main')[0];
var res = /[0-9]+/;
var match = res.exec(spans);
console.log(match); 
 }

I don't know how to proceed. The Regex is correct, the document. variable "spans" shows the correct result, but matching won't show any output in the console.

What am I missing?

spans in your code currently contains the whole element.

To use only the data-channel-id value, see the code below:

var spans = document.getElementsByTagName('main')[0].getAttribute('data-channel-id');

spans is not string but HTMLElement, to get value of data-channel-id you can use getAttribute as mentioned in comment above or if you really want to use regex convert it to string with .outerHTML

window.onload = function() {
  var spans = document.getElementsByTagName('main')[0];
  var res = /[0-9]+/;
  var match = res.exec(spans.outerHTML);
  console.log(match);
}

I want to get the number from "data-channel-id"

No need to use regex. Just:

var spans = document.getElementsByTagName('main')[0];
var match = spans.getAttribute('data-channel-id');
console.log(match); 

Working demo here .

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