2

I have a line that creates a simple box like so:

var box = $('<button>').addClass('box');

With using the css:

.box {
    border-radius: 0.7vw;
    width: 40vw;
    height: 50vw;
    margin: 30px;
    display: inline-block;
    background-color: #d87c2d;
}

All fine, I get those boxes, I can even click on them.

But what I really need is generating some usable elements.

For that, I usually like to keep components separate (hope I use the correct terminology), so I made a text file with the following content:

<div>
    <div class="tile" id="eventName"> Event name</div><br/>
    <div class="tile" id="eventDate">2017.01.01. </div>
    <div class="tile" id="eventTime">12.00</div><br/> 
    <div class="tile" id="description">Some boring example description about the meaningless </div>
</div>

My goal is to put this inside the $(-here-) instead of the simple <button> I have there.

To get that I tried

var box = $('/html/tileInside').addClass('box');

but didn't work, I believe JS thinks I want just the string /html/tileInside there which obviously doesn't mean anything.

So is there a way to add a string from a txt file inside the jQuery string selector?

5
  • there is no way jquery would know it is a string that somehow references some random file.... My guess is you want .load(), but I doubt that is what you really want.... Commented Oct 2, 2017 at 12:07
  • 4
    Just FYI the HTML you're trying to create is invalid. You cannot place a div within a button. Having a script in there isn't a great idea either - especially ones which repeatedly include the same JS files. Commented Oct 2, 2017 at 12:07
  • Thanks for the heads up. So after correcting the html, shall I just try to read the txt's content to a variable and put that inside? Or mess around with innerHTML? Commented Oct 2, 2017 at 12:10
  • 3
    As said, you cannot access a random file with javascript that simple. Consider using ajax $('<button>').load('/html/tileInside'); ...and yes, button as wrapper for script is kinda bad. Commented Oct 2, 2017 at 12:10
  • @sofl Thanks, it works. Do you want to convert that to an answer? Commented Oct 2, 2017 at 12:18

1 Answer 1

2

Use ajax here.

$('<div></div>').load('/html/tileInside');

http://api.jquery.com/load/

http://api.jquery.com/jQuery.ajax/

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

1 Comment

It even works if I use .html instead of a .txt. Great hint, thanks again.

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.