0

I want to extract the name value (which by the way happens to be randomly generated in this case) and be able to use this value as a javascript variable.

The HTML would look something like this:

<map name="20934948">

I want to get this 20934948 value and use that as a variable.

Example:

var myCustomVariableName = extracted javascript

So then in this case, myCustomVariableName would be 20934948.

3
  • 1
    extracted javascript - clearly that won't work ... but document.querySelector('map').name will get you the name of the first map in the document Commented Jul 20, 2018 at 3:35
  • Thank you! Exactly what I needed! My guess was document.querySelector('map name').value; but I thought that wasn't right so I asked. Commented Jul 20, 2018 at 3:36
  • @sdsdc I was typing up an answer to your other question, but you deleted it too soon. It's a slightly tricky problem which is why I couldn't answer it sooner. Commented Jul 20, 2018 at 5:39

2 Answers 2

1
// Get the map element
var m = document.getElementsByTagName('map')[0];

// Get the name of the map element
console.log(m.name);
Sign up to request clarification or add additional context in comments.

2 Comments

interesting. Looks like I could also use this by defining another variable as m.name, like, var myCustomVar = m.name after using your first line. Would upvote also if I had 15 points.
var myCustomVar = document.getElementsByTagName('map')[0].name; // But do not use this when you need the element for other things. Dont query the DOM with (document.getElementsBy... or document.querySelector...) for the same element multiple times.
0

Plain javascript:

var myCustomVariableName = document.querySelector('map').name;
console.log(myCustomVariableName);

Using jQuery:

$(function(){
  var jQueryReturn = $('map').attr('name');
  console.log(jQueryReturn);
});

var myCustomVariableName = document.querySelector('map').name;
console.log('plain JS : ' + myCustomVariableName);

$(function(){
  var jQueryReturn = $('map').attr('name');
  console.log('jQuery : ' + jQueryReturn);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<map name="20934948">

Comments

Your Answer

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