noahfaria
noahfaria

Reputation: 21

How to turn an element into a variable

<div class="font-bold uppercase mt-8">Upcoming Release</div>

Hey so I am trying to turn text on a website into a varable.

The part that I am trying to get is the "Upcoming release" and make it equal to the variable "question"

This is the current code that I have

var question = document.getElementsByClassName('font-bold uppercase mt-8')

I have tried many things but nothing seems to work.

UPDATE!!!

So I tried running this code in order to search the question in google after a specific set of time.

function searchQuestion() {
var question = document.getElementsByClassName('mb-4 font-bold');
    for (var i = 0; i < question.length; i++) {
    var text = question[i].innerText;
     console.log(text);
  }
  
  window.open('https://google.com/search?q='+text, '_blank');  
}

setTimeout(searchQuestion, 5000);

At this current moment in time, the element mb-4 font-bold does NOT exist yet, but while testing, it is picking up the element mb-4 text-3xl cols:text-5xl font-bold leading-none and it is searching what is in that element rather than what it is in mb-4 font-bold. How do I make it so that it ONLY searches the element mb-4 font-bold

If the element doesn't exist yet shouldn't it just search undefinded?

I am a new coder so any and all help will be taken into consideration. Thankyou

Upvotes: 1

Views: 150

Answers (2)

hgb123
hgb123

Reputation: 14891

Document.getElementsByClassName() return a list of elements, so in your case, to get the first one only, use destructing assignment to grab that

var [question] = document.getElementsByClassName('font-bold uppercase mt-8')

console.log(question)
<div class="font-bold uppercase mt-8">Upcoming Release</div>


Reference

Document.getElementsByClassName()

returns an array-like object of all child elements which have all of the given class name(s)

Destructuring assignment

const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2

Upvotes: 1

Devsi Odedra
Devsi Odedra

Reputation: 5322

getElementsByClassName will returns an array of elements.

var question = document.getElementsByClassName('font-bold uppercase mt-8');
for (var i = 0; i < question.length; i++) {
  var text = question[i].innerText;
   console.log('text => ', text);
}
<div class="font-bold uppercase mt-8">Upcoming Release</div>

Upvotes: 1

Related Questions