-2

How can I get the '123' value from the following code? I thought the snippet should work but I instead get email :....

<div id="home">
    <div class="name" my-data="123">Email: test@gmail.com</div> 
</div>

var element = document.querySelector('.element');
var dataAttribute = element.getAttribute('my-data');

console.log(dataAttribute);
theoseo
  • 19
  • 1
  • 3
  • if you change the HTML to `class="email"` (as that's what the JS is looking for) [then it works](https://jsbin.com/hiloriqazu/edit?html,js,console) – VLAZ Oct 19 '21 at 10:27
  • Thanks, and how can I get the email string instead? @VLAZ – theoseo Oct 19 '21 at 10:34
  • By *not* getting the attribute value. [How to get the pure text without HTML element using JavaScript?](https://stackoverflow.com/q/6743912) | [How can get the text of a div tag using only javascript (no jQuery)](https://stackoverflow.com/q/10370204) – VLAZ Oct 19 '21 at 10:38
  • Isn't this just a typo? The code works after using the correct class name. – jabaa Oct 19 '21 at 10:44

2 Answers2

0

You try to use querySelector with .element, that class doens't exist instead you need to use .name

var element = document.querySelector('.name');
var dataAttribute = element.getAttribute('my-data');

console.log(dataAttribute);
<div id="home">
    <div class="name" my-data="123">Email: test@gmail.com</div> 
</div>

Just for your knowledge you could use data-attribute like this:

var element = document.querySelector('.name');
var dataAttribute = element.getAttribute('data-email');

console.log(dataAttribute);
<div id="home">
    <div class="name" data-email="123">Email: test@gmail.com</div> 
</div>

Reference:


For pick text of div email use textContent like:

var element = document.querySelector('.name');
var dataAttribute = element.getAttribute('my-data');

console.log(dataAttribute, element.textContent);
<div id="home">
    <div class="name" my-data="123">Email: test@gmail.com</div> 
</div>

Reference:

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
0

When using a custom attribute, make sure to write "data-", and then the rest of the attribute name. Doing that, you can easily access the data from javascript.

<div class="name" data-something="123">Email: test@gmail.com</div> 

And for the js:

let element = document.querySelector('.name')
let dataAttribute = element.dataset.something
Noex98
  • 166
  • 6
  • thanks, any idea how I can get the text content of the div (Email) with JS? – theoseo Oct 19 '21 at 12:09
  • `let text = element.textContent` – Noex98 Oct 19 '21 at 12:24
  • Thanks, do. you know how I can add a cookie to that email which expires in 2 months ? I think the code should be something like this but I do not how to add the value of the email: function myemail () { var expiryDate = new Date(); expiryDate.setMonth(expiryDate.getMonth() + 2); document.cookie = cookieName + '=y; expires=' + expiryDate.toGMTString – theoseo Oct 19 '21 at 12:37