Access sub div Javascript

Asked

Viewed 29 times

0

<div class="container">
  <div class="card-deck mb-3 text-center">
     <div class="card mb-4 box-shadow">
      <div class="card-header">
        <h4 class="my-0 font-weight-normal">Lights</h4>
      </div>
      <div class="card-body">
        <div id="relay">

        </div>
      </div>
    </div>
</div>
</div>

This is my HTML, and I intend to add a button in the div relay, but I don’t know how to access it with javascript.

My javascript is something like this

if(1 == 1){ //ignorem esta comparação
    document.getElementById('relay').innerHTML='<button type='button'  class='btn btn-lg btn-block btn-outline-danger'>OFF</button>';
}else{ 
    document.getElementById('relay').innerHTML='<button type='button' class='btn btn-lg btn-block btn-outline-success'>ON</button>';
}
  • Did you manage to resolve the question? If yes, please tick the answer. Obg!

1 answer

3

You have to use double quotes to delimit the string, since inside it you are using single quotes:

...="<button type='button'  class='btn btn-lg btn-block btn-outline-danger'>OFF</button>";
    ↑                                                                                   ↑

In this line also:

...="<button type='button' class='btn btn-lg btn-block btn-outline-success'>ON</button>";
    ↑                                                                                  ↑

Or else you would have to escape all the simple quotes from the string, which is not the best output:

...='<button type=\'button\' class=\'btn btn-lg btn-block btn-outline-success\'>ON</button>';
  • I used single quotes, because this code is embedded in the Norwegian, and in turn, each line already has double quotes like this javaScript+=" message = xmldoc[0].firstChild.nodeValue;\n";

  • Got it... just a second I’m gonna check...

  • So do as I put it in the same answer, but escape the double quotes, like this: document.getElementById('relay').innerHTML=\"<button type='button' class='btn btn-lg btn-block btn-outline-danger'>OFF</button>\";

  • do I escape only at the beginning and at the end? I think you were wrong to write...

  • If I understand the question, I believe it is escaping the double quotes. This code is inside the variable javaScript, that’s not it?

  • Yes that’s it. But the way to add the <button> à div relay is the way to do with the document.getElementById('relay').innerHTML=... ?

  • Yeah, that’s one way to do it.

  • Managed to solve?

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.