1

I'm new in javascript development and I want to ask how to set variable from text method.

Example: in this code have a text method

        $('.phone').text(theRestaurant.phone);
        $('.location').text(theRestaurant.location);
        $('.info').text(theRestaurant.info);

in the Html file, when I create any class from these will print the value from JSON file.

Example :

        <div class='phone'></div>

Output: (000)000-9999

source code:

        <div class='phone'>(000)000-9999</div>

I try to set this in variable but it doesn't work.

My try:

        var phone = theRestaurant.phone

I want to set it in variable because I need to put it inside href value like so:

<script>
    var phone = 'tel:' + phone
    document.getElementById("phone").href = phone;
</script>

I hope everything clear. and If have an other solution please tell about it.

Thanks

6
  • 1
    document.getElementsByClassName("phone").href = phone ? (You wrote ByID) Commented Apr 14, 2016 at 0:49
  • Ok, now when I type in console: phone, it give me <h6 id="phone">744-xxxxxx</h6> I set the style for h6 display:none can I put the value of h6 in side href="tel:__number_here__" Commented Apr 14, 2016 at 1:30
  • 1
    You can't have multiple elements with same ID. But considering you have <a class="phone">, you can do: var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone; Commented Apr 14, 2016 at 1:47
  • You are 100% right, but that if I type manually in id class it works, but because the data coms from json, it give me empty value Commented Apr 14, 2016 at 2:01
  • 1
    Its works now, I put it in the main file. Thank you very much for your help Commented Apr 14, 2016 at 2:04

2 Answers 2

1

Have you wrapped your jQuery code in a document.ready() wrapper?

If not, then the javascript might run before the page has had time to create the elements in the DOM, and nothing will work.

<script>
$(document).ready(function(){
     //all javascript/jQuery code goes in here
});
</script>

Also, see my comment above about mixing up "ByClassName" and "ByID"

Sign up to request clarification or add additional context in comments.

2 Comments

the reason of my question that how to store the data in variable. I know that I type by id, but even if I set by class doesn't work
when I type in the browser console: phone, it give me error
0

Answer came from @itsgoingdown

this code in main javascript file:

var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.